Home > Article > Backend Development > How to implement Kruskal's algorithm using Python?
How to implement Kruskal's algorithm using Python?
Introduction:
Kruskal's algorithm is a classic algorithm for solving the minimum spanning tree, which can find the spanning tree with the minimum total weight in a given weighted connected graph. This article will introduce how to implement Kruskal's algorithm using Python and provide detailed code examples.
class Graph: def __init__(self, vertices): self.V = vertices # 顶点数 self.graph = [] # 添加边 def add_edge(self, u, v, weight): self.graph.append([u, v, weight]) # 查找根节点 def find(self, parent, i): if parent[i] == i: return i return self.find(parent, parent[i]) # 合并集合 def union(self, parent, rank, x, y): root_x = self.find(parent, x) root_y = self.find(parent, y) if rank[root_x] < rank[root_y]: parent[root_x] = root_y elif rank[root_x] > rank[root_y]: parent[root_y] = root_x else: parent[root_y] = root_x rank[root_x] += 1 # 克鲁斯卡尔算法 def kruskal_algorithm(self): result = [] i = 0 e = 0 self.graph = sorted(self.graph, key=lambda item: item[2]) # 按照权值排序 parent = [] rank = [] for node in range(self.V): parent.append(node) rank.append(0) while e < self.V - 1: u, v, weight = self.graph[i] i += 1 x = self.find(parent, u) y = self.find(parent, v) if x != y: e += 1 result.append([u, v, weight]) self.union(parent, rank, x, y) # 打印最小生成树 print("最小生成树:") for u, v, weight in result: print(f"{u} -- {v} {weight}") # 计算最小生成树的总权值 total_weight = sum(weight for u, v, weight in result) print("最小生成树的总权值:", total_weight) if __name__ == '__main__': g = Graph(6) g.add_edge(0, 1, 4) g.add_edge(0, 2, 3) g.add_edge(1, 2, 1) g.add_edge(1, 3, 2) g.add_edge(2, 3, 4) g.add_edge(2, 4, 3) g.add_edge(3, 4, 2) g.add_edge(3, 5, 1) g.add_edge(4, 5, 6) g.kruskal_algorithm()
Conclusion:
Kruskal's algorithm is an efficient method for solving the minimum spanning tree of a connected graph. By sorting the edges and merging the sets, you can get a minimum spanning tree with the minimum total Spanning tree of weights. Using Python to implement Kruskal's algorithm can help us better understand the principles and processes of the algorithm, and easily apply it to practical problems.
The above is the detailed content of How to implement Kruskal's algorithm using Python?. For more information, please follow other related articles on the PHP Chinese website!