Tuesday, 08 October 2024

P Programming

What is the Kruskal algorithm?

Star InactiveStar InactiveStar InactiveStar InactiveStar Inactive
 

Kruskal's algorithm is a graph algorithm that is used to find the minimum spanning tree in a weighted graph. Spanning tree as a subset of the edges of a graph includes all the vertices of the graph and establishes the connection between the vertices without having any distance.

Kruskal's algorithm works step by step and at each step, it adds the edge that has the lowest weight and connects two different vertices to the spanning tree. This continues until all vertices of the spanning tree are connected or until there are no more edges to add.

 

The Kruskal algorithm usually uses a data structure called "Union-Find" to track and merge different sets of vertices. This data structure allows the algorithm to quickly check whether adding an edge connecting two vertices creates a circle. Using the Kruskal algorithm, it is possible to find the minimum spanning tree in a weighted graph. This algorithm is used in issues such as networking, network design and routing optimization.

 

Implementation of the Kruskal algorithm

Kruskal algorithm can be implemented using different programming languages. Below is an example implementation of the Kruskal algorithm in Python:

 

class UnionFind:

 

 def __init__(self, vertices):

 

 self.parent = {}

 

 self.rank = {}

 

 for v in vertices:

 

 self.parent[v] = v

 

 self.rank[v] = 0

 

 def find(self, v):

 

 if self.parent[v] != v:

 

 self.parent[v] = self.find(self.parent[v])

 

 return self.parent[v]

 

 def union(self, v1, v2):

 

 root1 = self.find(v1)

 

 root2 = self.find(v2)

 

 if root1 != root2:

 

 if self.rank[root1] < self.rank[root2]:

 

 self.parent[root1] = root2

 

 elif self.rank[root1] > self.rank[root2]:

 

 self.parent[root2] = root1

 

 otherwise:

 

 self.parent[root2] = root1

 

 self.rank[root1] += 1

 

def kruskal(graph):

 

 minimum_spanning_tree = []

 

 edges = []

 

 for u in graph:

 

 for v, weight in graph[u]:

 

 edges.append((u, v, weight))

 

 edges.sort(key=lambda x: x[2])

 

 vertices = set()

 

 for edge in edges:

 

 u, v, weight = edge

 

 vertices.add(u)

 

 vertices.add(v)

 

 uf = UnionFind(vertices)

 

 for edge in edges:

 

 u, v, weight = edge

 

 if uf.find(u) != uf.find(v):

 

 uf. union(u, v)

 

 minimum_spanning_tree.append(edge)

 

 return minimum_spanning_tree

 

In this implementation, first, a class called UnionFind is defined that uses the union order data structure to track and merge different collections. Then, the kruskal function is defined which implements the Kruskal

 

algorithm. This function receives an input graph and returns the minimum spanning tree. To use this implementation, you can define your own weighted graph and give it as input to the kruskal function. Then, the minimum spanning tree will be received as output. The input values ​​and graph must be properly defined for the implementation to work correctly.

 

Steps of the algorithm implementation process

The steps of Kruskal's algorithm are as follows:

 

1. Prepare the data structure:

 

 Create an empty collection to store the minimum spanning tree (minimum_spanning_tree).

 Create an empty list to store the edges of the graph.

2. Create the list of edges of the graph:

 

 For each vertex u in the graph:

 For each edge (v, weight) connected to u:

 Add edge (u, v, weight) to list of edges.

3. Sorting the list of edges based on the weight of each edge. (Ascending Sort)

 

4. Prepare the Union-Find data structure:

 

 For each vertex in the graph, create a node in union order and set it as its parent.

 Set a rank of zero for each node in the union order.

5. Examination of edges in order from the lowest weight to the highest weight:

 

 For each edge (u, v, weight) in the list of edges:

 If the union order is different from u and v (i.e., adding this edge to the spanning tree does not produce a minimum spanning tree):

 Add edge (u, v, weight) to the minimum spanning tree.

 Update the union order of u and v (that is, join them together).

6. Return the minimum spanning tree as output.

 

In these steps, the Kruskal algorithm examines the edges of the graph in order from the lowest weight to the highest weight and adds these edges to the minimum spanning tree. The union-order data structure is used to more efficiently perform edge-adding and edge-presence operations. In this way, you finally get the minimum spanning tree with minimum weight.

 

An example of Kruskal's algorithm

As an example, suppose we have the following graph:

 

 A---2---B

 

 / \ /

 

 1 3 4

 

 / \ /

 

C---5---D

 

Now we want to run the Kruskal algorithm on this graph to get the minimum spanning tree. We execute the steps in order:

 

1. We prepare the data structure:

 

minimum_spanning_tree = []

 

edges = []

 

2. Make a list of graph edges:

 

 For A: Add (A, B, 2) to the list of edges

 For A: Add (A, C, 1) to the list of edges

 For B: Add (B, D, 4) to the list of edges

 For C: Add (C, D, 5) to the list of edges

 For D: Add (D, B, 3) to the list of edges

 List of edges: [(A, B, 2), (A, C, 1), (B, D, 4), (C, D, 5), (D, B, 3)]

 

3. Sorting the list of edges based on the weight of each edge:

 

 List of edges: [(A, C, 1), (A, B, 2), (D, B, 3), (B, D, 4), (C, D, 5)]

4. We prepare the union order data structure:

 

Vertex A: parent = A, rank = 0

 

Vertex B: parent = B, rank = 0

 

Vertex C: parent = C, rank = 0

 

Vertex D: parent = D, rank = 0

 

5. Examination of edges in order from the lowest weight to the highest weight:

 

 (A, C, 1): The union order of A and C is different, so we add the edge to the minimum spanning tree and update the union order.

 (A, B, 2): The union order of A and B is different, so we add the edge to the minimum spanning tree and update the union order.

 (D, B, 3): The union order of D and B is different, so we add the edge to the minimum spanning tree and update the union order.

 (B, D, 4): The union order of B and D is the same, so adding this edge to the spanning tree produces a minimum spanning tree. Now the minimum spanning tree is as follows:

 A---2---B

 

 /

 

 1

 

 /

 

 c

 

6. Remains. (C, D, 5): The union order of C and D is different, so we add the edge to the minimum spanning tree and update the union order. Finally, the minimum spanning tree will be as follows:

 

 A---2---B

 

 / \

 

 1 4

 

 / \

 

 C---5---D

 

In this example, the Kruskal algorithm examines the edges of the graph and ignores the edges that are involved in creating a cycle in the minimum spanning tree. Finally, we get the minimum spanning tree with minimum weight.

 

Coded examples of the Kruskal algorithm

 

 

Kruskal's algorithm to find the minimum spanning tree of a graph can be implemented using a data structure such as Union-Find. Below is an example of Kruskal algorithm coding using Python programming language:

 

# Class to display an edge in the graph

 

class Edge:

 

 def __init__(self, src, dest, weight):

 

 self.src = src

 

 self.dest = dest

 

 self.weight = weight

 

# Class to display a complete graph

 

Graph class:

 

 def __init__(self, vertices):

 

 self.V = vertices

 

 self.edges = []

 

 def add_edge(self, src, dest, weight):

 

 edge = Edge(src, dest, weight)

 

 self.edges.append(edge)

 

# Class to display a set of union order

 

class UnionFind:

 

 def __init__(self, vertices):

 

 self.parent = {}

 

 self.rank = {}

 

 for v in vertices:

 

 self.parent[v] = v

 

 self.rank[v] = 0

 

 def find(self, v):

 

 if self.parent[v] != v:

 

 self.parent[v] = self.find(self.parent[v])

 

 return self.parent[v]

 

 def union(self, v1, v2):

 

 root1 = self.find(v1)

 

 root2 = self.find(v2)

 

 if self.rank[root1] < self.rank[root2]:

 

 self.parent[root1] = root2

 

 elif self.rank[root1] > self.rank[root2]:

 

 self.parent[root2] = root1

 

 otherwise:

 

 self.parent[root2] = root1

 

 self.rank[root1] += 1

 

# Kruskal's algorithm to find the minimum spanning tree

 

def kruskal_algorithm(graph):

 

 minimum_spanning_tree = []

 

 graph.edges = sorted(graph.edges, key=lambda edge: edge.weight)

 

 # Sort edges by weight

 

 union_find = UnionFind(list(range(graph.V)))

 

# Create a union order for the vertices

 

 for edge in graph.edges:

 

 src_root = union_find.find(edge.src)

 

 dest_root = union_find.find(edge.dest)

 

 if src_root != dest_root:

 

# If the order of union of two vertices is different

 

 minimum_spanning_tree.append(edge)

 

 # Add edge to minimum spanning tree

 

 union_find.union(src_root, dest_root)

 

# Merge two vertices

 

 return minimum_spanning_tree

 

# Example of using the Kruskal algorithm

 

g = Graph(4)

 

g.add_edge(0, 1, 2)

 

g.add_edge(0, 2, 1)

 

g.add_edge(1, 2, 3)

 

g.add_edge(1, 3, 4)

 

g.add_edge(2, 3, 5)

 

minimum_spanning_tree = kruskal_algorithm(g)

 

# Show minimum spanning tree

 

for edge in minimum_spanning_tree:

 

 print(f"{edge.src} -- {edge.dest} : {edge.weight}")

 

 

This Python code includes three classes: Edge, Graph and UnionFind. The Edge class is used to represent each edge in the graph, the Graph class is used to represent a complete graph with functions to add edges to the graph, and the UnionFind class is used to represent a set of union sequences. Then, the Kruskal algorithm is implemented with the kruskal_algorithm function. This algorithm calculates the minimum spanning tree by using union order and sorting edges based on weight. Finally, the minimum spanning tree is displayed. To use the Kruskal algorithm, an instance of the Graph class is created and edges are added to it using the add_edge function. Then the kruskal_algorithm function is called and the minimum spanning tree is displayed. In the above example, the edges and their weights are strictly defined. You can define your input as needed and run the algorithm.

Applications of Kruskal Algorithm

Kruskal's algorithm is an important algorithm in the field of graphs and is used to find the minimum spanning tree of a graph. This algorithm is used in many problems and applications. Below, I mention some applications of the Kruskal algorithm:

 

 Cable networks: Kruskal's algorithm can be used in planning and designing cable networks. Using the Kruskal algorithm, a minimum spanning tree can be established to connect cables between different points in a network. This spanning tree provides the most optimal paths for data transmission and minimizes cabling costs.

 Communication networks: In the design of communication networks, the Kruskal algorithm is used to select optimal connections between centers and equipment. Using the Kruskal algorithm, we can construct a minimum spanning tree for the communication between centers and equipment in the network, which minimizes the communication cost and improves the network performance.

 Traffic and transportation: In planning and optimizing transportation and traffic related issues, Kruskal algorithm can be used. Using the Kruskal algorithm, we can construct a minimum spanning tree for connecting roads, transportation routes, or traffic networks that minimize travel time and cost and improve traffic flow.

 Social networks: Kruskal's algorithm can be used in the analysis and review of social networks. Using this algorithm, it is possible to identify a set of important relationships and strong connections between people in social networks.

 Image processing: Kruskal's algorithm can also be used in some image processing problems. For example, this algorithm can be used to detect and connect different components of an image (such as object tracking, 3D imaging, etc.).

 Scheduling: In scheduling and project planning, the Kruskal algorithm can be used to determine the order and priority of activities and tasks.

 Optimization problems: Kruskal algorithm is used in solving optimization problems. By using this algorithm, we can solve problems that are related to the concept of graph in a general and optimal way.

 Solving minimization problems: Kruskal's algorithm can be used to solve minimization problems. For example, this algorithm can be used to find the shortest path between two points in a network.

 

The mentioned cases are only a few examples of the applications of the Kruskal algorithm, and in practice, this algorithm can be used in many other problems as well.