How to implement the minimum spanning tree algorithm using java
How to use Java to implement the minimum spanning tree algorithm
The minimum spanning tree algorithm is a classic problem in graph theory, used to solve the minimum of a weighted connected graph spanning tree. This article will introduce how to use Java language to implement this algorithm and provide specific code examples.
- Problem Description
Given a connected graph G, in which each edge has a weight, it is required to find a minimum spanning tree T such that the sum of the weights of all edges in T is the smallest. - Prim algorithm
Prim algorithm is a greedy algorithm used to solve the minimum spanning tree problem. Its basic idea is to start from a vertex and gradually expand the spanning tree, selecting the vertex closest to the existing spanning tree each time until all vertices are added to the spanning tree.
The following is a Java implementation example of Prim's algorithm:
import java.util.ArrayList; import java.util.List; import java.util.PriorityQueue; import java.util.Queue; class Edge implements Comparable<Edge> { int from; int to; int weight; public Edge(int from, int to, int weight) { this.from = from; this.to = to; this.weight = weight; } @Override public int compareTo(Edge other) { return Integer.compare(this.weight, other.weight); } } public class Prim { public static List<Edge> calculateMST(List<List<Edge>> graph) { int n = graph.size(); boolean[] visited = new boolean[n]; Queue<Edge> pq = new PriorityQueue<>(); // Start from vertex 0 int start = 0; visited[start] = true; for (Edge e : graph.get(start)) { pq.offer(e); } List<Edge> mst = new ArrayList<>(); while (!pq.isEmpty()) { Edge e = pq.poll(); int from = e.from; int to = e.to; int weight = e.weight; if (visited[to]) { continue; } visited[to] = true; mst.add(e); for (Edge next : graph.get(to)) { if (!visited[next.to]) { pq.offer(next); } } } return mst; } }
- Kruskal algorithm
Kruskal algorithm is also a greedy algorithm used to solve the minimum spanning tree problem. Its basic idea is to sort all the edges in the graph according to the weight from small to large, and then add them to the spanning tree in turn. When adding an edge, if the two endpoints of the edge do not belong to the same connected component, then these edges can be added to the spanning tree. The two endpoints merge into a connected component.
The following is a Java implementation example of Kruskal's algorithm:
import java.util.ArrayList; import java.util.Collections; import java.util.List; class Edge implements Comparable<Edge> { int from; int to; int weight; public Edge(int from, int to, int weight) { this.from = from; this.to = to; this.weight = weight; } @Override public int compareTo(Edge other) { return Integer.compare(this.weight, other.weight); } } public class Kruskal { public static List<Edge> calculateMST(List<Edge> edges, int n) { List<Edge> mst = new ArrayList<>(); Collections.sort(edges); int[] parent = new int[n]; for (int i = 0; i < n; i++) { parent[i] = i; } for (Edge e : edges) { int from = e.from; int to = e.to; int weight = e.weight; int parentFrom = findParent(from, parent); int parentTo = findParent(to, parent); if (parentFrom != parentTo) { mst.add(e); parent[parentFrom] = parentTo; } } return mst; } private static int findParent(int x, int[] parent) { if (x != parent[x]) { parent[x] = findParent(parent[x], parent); } return parent[x]; } }
- Example usage
The following is a simple example usage:
import java.util.ArrayList; import java.util.List; public class Main { public static void main(String[] args) { List<List<Edge>> graph = new ArrayList<>(); graph.add(new ArrayList<>()); graph.add(new ArrayList<>()); graph.add(new ArrayList<>()); graph.add(new ArrayList<>()); graph.get(0).add(new Edge(0, 1, 2)); graph.get(0).add(new Edge(0, 2, 3)); graph.get(1).add(new Edge(1, 0, 2)); graph.get(1).add(new Edge(1, 2, 1)); graph.get(1).add(new Edge(1, 3, 5)); graph.get(2).add(new Edge(2, 0, 3)); graph.get(2).add(new Edge(2, 1, 1)); graph.get(2).add(new Edge(2, 3, 4)); graph.get(3).add(new Edge(3, 1, 5)); graph.get(3).add(new Edge(3, 2, 4)); List<Edge> mst = Prim.calculateMST(graph); System.out.println("Prim算法得到的最小生成树:"); for (Edge e : mst) { System.out.println(e.from + " -> " + e.to + ",权重:" + e.weight); } List<Edge> edges = new ArrayList<>(); edges.add(new Edge(0, 1, 2)); edges.add(new Edge(0, 2, 3)); edges.add(new Edge(1, 2, 1)); edges.add(new Edge(1, 3, 5)); edges.add(new Edge(2, 3, 4)); mst = Kruskal.calculateMST(edges, 4); System.out.println("Kruskal算法得到的最小生成树:"); for (Edge e : mst) { System.out.println(e.from + " -> " + e.to + ",权重:" + e.weight); } } }
By running the above example program, you can get the following output:
Prim算法得到的最小生成树: 0 -> 1,权重:2 1 -> 2,权重:1 2 -> 3,权重:4 Kruskal算法得到的最小生成树: 1 -> 2,权重:1 0 -> 1,权重:2 2 -> 3,权重:4
The above is a specific code example of using Java to implement the minimum spanning tree algorithm. Through these sample codes, readers can better understand and learn the implementation process and principles of the minimum spanning tree algorithm. Hope this article is helpful to readers.
The above is the detailed content of How to implement the minimum spanning tree algorithm using java. 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



How to use Java to implement dynamic programming algorithm Dynamic programming is an optimization method for solving multi-stage decision-making problems. It decomposes the problem into multiple stages. Each stage makes a decision based on known information and records the results of each decision so that used in subsequent stages. In practical applications, dynamic programming is usually used to solve optimization problems, such as shortest path, maximum subsequence sum, knapsack problem, etc. This article will introduce how to use Java language to implement dynamic programming algorithms and provide specific code examples. 1. Basic principles of dynamic programming algorithms

How to use PHP to develop simple SEO optimization functions SEO (SearchEngineOptimization), or search engine optimization, refers to improving the website's ranking in search engines by improving the structure and content of the website, thereby obtaining more organic traffic. In website development, how to use PHP to implement simple SEO optimization functions? This article will introduce some commonly used SEO optimization techniques and specific code examples to help developers implement SEO optimization in PHP projects. 1. Friendly to use

How to use C# to write the minimum spanning tree algorithm. The minimum spanning tree algorithm is an important graph theory algorithm, which is used to solve the connectivity problem of graphs. In computer science, a minimum spanning tree refers to a spanning tree of a connected graph in which the sum of the weights of all edges of the spanning tree is the smallest. This article will introduce how to use C# to write the minimum spanning tree algorithm and provide specific code examples. First, we need to define a graph data structure to represent the problem. In C#, you can use an adjacency matrix to represent a graph. An adjacency matrix is a two-dimensional array in which each element represents

How to use Java to implement the RSA encryption algorithm RSA (Rivest-Shamir-Adleman) is an asymmetric encryption algorithm, which is one of the most commonly used encryption algorithms currently. This article will introduce how to use Java language to implement the RSA encryption algorithm and provide specific code examples. Generate a key pair First, we need to generate a pair of RSA keys, which consists of a public key and a private key. The public key can be used to encrypt data and the private key can be used to decrypt data. The following is a code example to generate an RSA key pair: import

How to use Java to implement Kruskal's algorithm Kruskal's algorithm is an algorithm commonly used to solve the minimum spanning tree problem. It uses edges as the entry point to gradually build a minimum spanning tree. In this article, we will detail how to implement Kruskal's algorithm using Java and provide specific code examples. Algorithm Principle The basic principle of Kruskal's algorithm is to sort all edges in order of weight from small to large, and then select edges in order of weight from small to large, but cannot form a cycle. The specific implementation steps are as follows:

Java implementation of the examination arrangement adjustment function of the online examination system Introduction: With the development of Internet technology, more and more schools and training institutions choose to use online examination systems for examinations and assessments. Examination schedule adjustment is an important function in the online examination system, which can help administrators flexibly adjust examination time and examination-related information according to the actual situation. This article will introduce in detail how to use Java programming to implement the examination schedule adjustment function of the online examination system, and give specific code examples. Database design exam arrangement adjustment function needs

With the development of the Internet, the amount of data on the network has exploded, making it difficult for users to quickly and accurately find the content they really need when faced with a large amount of information. Recommendation algorithms emerged as the times require, and provide users with personalized services and recommended content by recording and analyzing user behavior data, thereby improving user satisfaction and loyalty. As the language of choice for large-scale software development, Java is also popular in the implementation of recommendation algorithms. 1. Recommendation algorithm The recommendation algorithm is a method that analyzes and mines user interaction, behavior and interest data.

One-click solution: Quickly master the usage skills of pip mirror source Introduction: pip is the most commonly used package management tool for Python, which can easily install, upgrade and manage Python packages. However, due to well-known reasons, using the default mirror source to download the installation package is slower. In order to solve this problem, we need to use a domestic mirror source. This article will introduce how to quickly master the usage skills of pip mirror source and provide specific code examples. Before you start, understand the concept of pip mirror source.
