|
| 1 | +graph folder structure: |
| 2 | +graph/ |
| 3 | +__init__.py |
| 4 | +graph.py |
| 5 | +kruskal.py |
| 6 | + |
| 7 | +graph.py: |
| 8 | +class Graph: |
| 9 | + def __init__(self, vertices): |
| 10 | + self.V = vertices |
| 11 | + self.graph = [] |
| 12 | + |
| 13 | + def addEdge(self, u, v, w): |
| 14 | + self.graph.append([u, v, w]) |
| 15 | + |
| 16 | +kruskal.py: |
| 17 | +from .graph import Graph |
| 18 | + |
| 19 | +class Kruskal: |
| 20 | + def __init__(self, graph): |
| 21 | + self.graph = graph |
| 22 | + |
| 23 | + def find(self, parent, i): |
| 24 | + if parent[i] != i: |
| 25 | + parent[i] = self.find(parent, parent[i]) |
| 26 | + return parent[i] |
| 27 | + |
| 28 | + def union(self, parent, rank, x, y): |
| 29 | + if rank[x] < rank[y]: |
| 30 | + parent[x] = y |
| 31 | + elif rank[x] > rank[y]: |
| 32 | + parent[y] = x |
| 33 | + else: |
| 34 | + parent[y] = x |
| 35 | + rank[x] += 1 |
| 36 | + |
| 37 | + def KruskalMST(self): |
| 38 | + result = [] |
| 39 | + i, e = 0, 0 |
| 40 | + self.graph.graph = sorted(self.graph.graph, key=lambda item: item[2]) |
| 41 | + parent = [] |
| 42 | + rank = [] |
| 43 | + |
| 44 | + for node in range(self.graph.V): |
| 45 | + parent.append(node) |
| 46 | + rank.append(0) |
| 47 | + |
| 48 | + while e < self.graph.V - 1: |
| 49 | + u, v, w = self.graph.graph[i] |
| 50 | + i = i + 1 |
| 51 | + x = self.find(parent, u) |
| 52 | + y = self.find(parent, v) |
| 53 | + |
| 54 | + if x != y: |
| 55 | + e = e + 1 |
| 56 | + result.append([u, v, w]) |
| 57 | + self.union(parent, rank, x, y) |
| 58 | + |
| 59 | + minimumCost = 0 |
| 60 | + print("Edges in the constructed MST") |
| 61 | + for u, v, weight in result: |
| 62 | + minimumCost += weight |
| 63 | + print("%d -- %d == %d" % (u, v, weight)) |
| 64 | + print("Minimum Spanning Tree", minimumCost) |
| 65 | + |
| 66 | +Usage: |
| 67 | +from graph import Graph |
| 68 | +from graph.kruskal import Kruskal |
| 69 | + |
| 70 | +if __name__ == '__main__': |
| 71 | + g = Graph(4) |
| 72 | + g.addEdge(0, 1, 10) |
| 73 | + g.addEdge(0, 2, 6) |
| 74 | + g.addEdge(0, 3, 5) |
| 75 | + g.addEdge(1, 3, 15) |
| 76 | + g.addEdge(2, 3, 4) |
| 77 | + |
| 78 | + k = Kruskal(g) |
| 79 | + k.KruskalMST() |
0 commit comments