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.
- Algorithm introduction:
The basic idea of Kruskal's algorithm is to sort all the edges in the connected graph according to their weights, and then select the edges from small to large. If the current edge selected is not If a loop is formed, it is added to the minimum spanning tree and marked as visited. Until the number of edges in the minimum spanning tree is equal to the number of vertices in the graph minus one. - Implementation steps:
(1) Define the class of the graph and initialize the number of vertices and edges of the graph.
(2) Define the class of each edge and initialize the starting point, end point and weight of the edge.
(3) Write a function to implement and initialize the set, including finding the root node and merging sets.
(4) Write the main function to implement Kruskal's algorithm, including sorting edges, selecting edges one by one to determine whether they form a cycle, adding edges to the minimum spanning tree, and calculating the total weight of the minimum spanning tree. - Code example:
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()
- Result analysis:
The above code is a typical example, which constructs a weighted undirected graph containing 6 vertices. And use Kruskal's algorithm to solve its minimum spanning tree. The program prints the edges in the minimum spanning tree and the total weight of the minimum spanning tree.
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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



Title: Use of Prim algorithm and code examples in C++ Introduction: Prim algorithm is a commonly used minimum spanning tree algorithm, mainly used to solve the minimum spanning tree problem in graph theory. In C++, Prim's algorithm can be used effectively through reasonable data structures and algorithm implementation. This article will introduce how to use Prim's algorithm in C++ and provide specific code examples. 1. Introduction to Prim algorithm Prim algorithm is a greedy algorithm. It starts from a vertex and gradually expands the vertex set of the minimum spanning tree until it contains

How to implement Huffman coding algorithm using Python? Abstract: Huffman coding is a classic data compression algorithm that generates unique codes based on the frequency of character occurrences, thereby achieving efficient compression and storage of data. This article will introduce how to use Python to implement the Huffman coding algorithm and provide specific code examples. Understand the idea of Huffman coding. The core idea of Huffman coding is to use slightly shorter codes for characters that appear more frequently, and to use slightly longer codes for characters that appear less frequently, so as to achieve coding.

Python method to implement the offline map download function in Baidu Map API With the rapid development of mobile Internet, the demand for offline map download function is becoming more and more urgent. The offline map download function allows users to still use map navigation and other functions without an Internet connection, giving users a better user experience. This article will introduce how to use Python to implement the offline map download function in Baidu Map API. Baidu Map API provides a complete set of open interfaces, including offline map download functions. In use

Use Python to implement Baidu AI interface docking to make your program smarter and more powerful. With the continuous development of artificial intelligence technology, more and more developers are beginning to implement intelligent functions to improve the intelligence of their programs. The Baidu AI interface is a powerful tool that can help us implement multiple intelligent functions such as speech recognition, image recognition, and natural language processing. This article will show you how to use Python to connect to Baidu AI interface to make your program smarter and more powerful. First, we need to go to Baidu AI Open Platform (h

In graph theory, finding the minimum spanning tree (MST) of a connected weighted graph is a common problem. MST is a subset of graph edges that connects all vertices and minimizes the total edge weight. An efficient algorithm to solve this problem is Boruvka algorithm. Syntax structEdge{intsrc,dest,weight;};//Definethestructuretorepresentasubsetforunion-findstructSubset{intparent,rank;};Algorithm Now, let us outline the steps involved in finding the minimum spanning tree in the Boruvka algorithm − Initialize the MST as an empty set. for each vertex

Python implements methods and case sharing for automated testing of web pages using headless browser collection applications Overview: In today's Internet era, automated web page testing has become one of the important means to improve software quality and efficiency. As a high-level programming language, Python has a wealth of third-party libraries and tools, making it easy and fast to use Python for automated testing of web pages. This article will introduce how to use a headless browser to collect applications and implement automated testing of web pages, and provide relevant code examples. 1. What is headless browsing?

Python implements page simulation click and scroll function analysis for headless browser collection applications. When collecting network data, it is often necessary to simulate user operations, such as clicking buttons, drop-down scrolling, etc. A common way to achieve these operations is to use a headless browser. A headless browser is actually a browser without a user interface that simulates user operations through programming. The Python language provides many libraries to implement headless browser operations, the most commonly used of which is the selenium library. selen

How to use greedy algorithm to achieve the optimal solution of minimum spanning tree problem in PHP? The minimum spanning tree (MinimumSpanningTree) problem is to find a subtree in a connected undirected graph such that this subtree contains all the vertices in the graph and the sum of the weights of all edges is the smallest. The greedy algorithm is one of the common methods to solve this problem. It gradually finds the global optimal solution by selecting the current optimal solution each time. First, we need to define a graph class to store the structure of the graph and the weights of the edges. The following is an example of
