|
| 1 | +# Class to represent a graph |
| 2 | +class Graph: |
| 3 | + def __init__(self, vertices): |
| 4 | + self.V = vertices # Number of vertices |
| 5 | + self.graph = [] # List to store graph edges (u, v, w) |
| 6 | + |
| 7 | + # Function to add an edge to the graph (u -> v with weight w) |
| 8 | + def add_edge(self, u, v, w): |
| 9 | + self.graph.append([u, v, w]) |
| 10 | + |
| 11 | + # Utility function to find set of an element i (uses path compression) |
| 12 | + def find(self, parent, i): |
| 13 | + if parent[i] == i: |
| 14 | + return i |
| 15 | + return self.find(parent, parent[i]) |
| 16 | + |
| 17 | + # Function that does union of two sets of x and y (uses union by rank) |
| 18 | + def union(self, parent, rank, x, y): |
| 19 | + root_x = self.find(parent, x) |
| 20 | + root_y = self.find(parent, y) |
| 21 | + |
| 22 | + # Attach smaller rank tree under the root of the high-rank tree |
| 23 | + if rank[root_x] < rank[root_y]: |
| 24 | + parent[root_x] = root_y |
| 25 | + elif rank[root_x] > rank[root_y]: |
| 26 | + parent[root_y] = root_x |
| 27 | + else: |
| 28 | + parent[root_y] = root_x |
| 29 | + rank[root_x] += 1 |
| 30 | + |
| 31 | + # Main function to construct MST using Kruskal's algorithm |
| 32 | + def kruskal_mst(self): |
| 33 | + # This will store the resultant Minimum Spanning Tree (MST) |
| 34 | + result = [] |
| 35 | + |
| 36 | + # Step 1: Sort all edges in non-decreasing order of their weight |
| 37 | + # If we are using a greedy algorithm, we need to sort the edges first |
| 38 | + self.graph = sorted(self.graph, key=lambda item: item[2]) |
| 39 | + |
| 40 | + # Allocate memory for creating V subsets (for the disjoint-set) |
| 41 | + parent = [] |
| 42 | + rank = [] |
| 43 | + |
| 44 | + # Create V subsets with single elements |
| 45 | + for node in range(self.V): |
| 46 | + parent.append(node) |
| 47 | + rank.append(0) |
| 48 | + |
| 49 | + # Number of edges in MST is V-1, so we will stop once we have V-1 edges |
| 50 | + e = 0 # Initialize result edges count |
| 51 | + i = 0 # Initialize the index for sorted edges |
| 52 | + |
| 53 | + # Loop until MST has V-1 edges |
| 54 | + while e < self.V - 1: |
| 55 | + # Step 2: Pick the smallest edge and increment the index for the next iteration |
| 56 | + u, v, w = self.graph[i] |
| 57 | + i = i + 1 |
| 58 | + |
| 59 | + # Step 3: Find sets of both vertices u and v (to check if adding this edge will form a cycle) |
| 60 | + x = self.find(parent, u) |
| 61 | + y = self.find(parent, v) |
| 62 | + |
| 63 | + # If adding this edge doesn't cause a cycle, include it in the result |
| 64 | + if x != y: |
| 65 | + result.append([u, v, w]) |
| 66 | + e = e + 1 # Increment the count of edges in the MST |
| 67 | + self.union(parent, rank, x, y) |
| 68 | + |
| 69 | + # Else, discard the edge (it would create a cycle) |
| 70 | + |
| 71 | + # Print the constructed Minimum Spanning Tree |
| 72 | + print("Following are the edges in the constructed MST:") |
| 73 | + for u, v, w in result: |
| 74 | + print(f"{u} -- {v} == {w}") |
| 75 | + |
| 76 | +# Example usage |
| 77 | +if __name__ == "__main__": |
| 78 | + V = int(input("Enter the number of vertices: ")) # Ask user for the number of vertices |
| 79 | + E = int(input("Enter the number of edges: ")) # Ask user for the number of edges |
| 80 | + |
| 81 | + g = Graph(V) # Create a graph with V vertices |
| 82 | + |
| 83 | + # Ask user to input the edges in the format u v w |
| 84 | + print("Enter each edge in the format: vertex1 vertex2 weight") |
| 85 | + for _ in range(E): |
| 86 | + u, v, w = map(int, input().split()) # Take input for edge (u, v) with weight w |
| 87 | + g.add_edge(u, v, w) |
| 88 | + |
| 89 | + # Print the constructed MST |
| 90 | + g.kruskal_mst() |
0 commit comments