├── Kruskal.py └── LICENSE /Kruskal.py: -------------------------------------------------------------------------------- 1 | class Graph: 2 | def __init__(self, vertices): 3 | self.V = vertices 4 | self.graph = [] 5 | 6 | def add_edge(self, u, v, w): 7 | self.graph.append([u, v, w]) 8 | 9 | def find(self, parent, i): 10 | if parent[i] == i: 11 | return i 12 | return self.find(parent, parent[i]) 13 | 14 | def union(self, parent, rank, x, y): 15 | xroot = self.find(parent, x) 16 | yroot = self.find(parent, y) 17 | 18 | if rank[xroot] < rank[yroot]: 19 | parent[xroot] = yroot 20 | elif rank[xroot] > rank[yroot]: 21 | parent[yroot] = xroot 22 | else: 23 | parent[yroot] = xroot 24 | rank[xroot] += 1 25 | 26 | def kruskal(self): 27 | result = [] 28 | i, e = 0, 0 29 | self.graph = sorted(self.graph, key=lambda item: item[2]) 30 | parent = [] 31 | rank = [] 32 | 33 | for node in range(self.V): 34 | parent.append(node) 35 | rank.append(0) 36 | 37 | while e < self.V - 1: 38 | u, v, w = self.graph[i] 39 | i += 1 40 | x = self.find(parent, u) 41 | y = self.find(parent, v) 42 | 43 | if x != y: 44 | e += 1 45 | result.append([u, v, w]) 46 | self.union(parent, rank, x, y) 47 | 48 | print("Edges in the constructed MST:") 49 | for u, v, weight in result: 50 | print(f"{u} -- {v} == {weight}") 51 | return result 52 | 53 | 54 | # Example Usage 55 | g = Graph(4) 56 | g.add_edge(0, 1, 10) 57 | g.add_edge(0, 2, 6) 58 | g.add_edge(0, 3, 5) 59 | g.add_edge(1, 3, 15) 60 | g.add_edge(2, 3, 4) 61 | 62 | mst = g.kruskal() 63 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2024 Alpha Roger (anshumansinha3301) 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | --------------------------------------------------------------------------------