最小生成树Java实现的代码
时间: 2024-04-21 15:22:06 浏览: 76
以下是一个使用Kruskal算法实现最小生成树的Java代码示例:
```java
import java.util.*;
class Edge implements Comparable<Edge> {
int src, dest, weight;
public int compareTo(Edge edge) {
return this.weight - edge.weight;
}
}
class Graph {
int V, E;
Edge[] edges;
Graph(int v, int e) {
V = v;
E = e;
edges = new Edge[E];
for (int i = 0; i < e; ++i)
edges[i] = new Edge();
}
int find(int[] parent, int i) {
if (parent[i] == -1)
return i;
return find(parent, parent[i]);
}
void union(int[] parent, int x, int y) {
int xset = find(parent, x);
int yset = find(parent, y);
parent[xset] = yset;
}
void kruskalMST() {
Edge[] result = new Edge[V];
int[] parent = new int[V];
for (int i = 0; i < V; ++i)
parent[i] = -1;
Arrays.sort(edges);
int e = 0;
int i = 0;
while (e < V - 1) {
Edge nextEdge = edges[i++];
int x = find(parent, nextEdge.src);
int y = find(parent, nextEdge.dest);
if (x != y) {
result[e++] = nextEdge;
union(parent, x, y);
}
}
System.out.println("边 权重");
for (i = 0; i < e; ++i)
System.out.println(result[i].src + " - " + result[i].dest + " " + result[i].weight);
}
public static void main(String[] args) {
int V = 4;
int E = 5;
Graph graph = new Graph(V, E);
graph.edges[0].src = 0;
graph.edges[0].dest = 1;
graph.edges[0].weight = 10;
graph.edges[1].src = 0;
graph.edges[1].dest = 2;
graph.edges[1].weight = 6;
graph.edges[2].src = 0;
graph.edges[2].dest = 3;
graph.edges[2].weight = 5;
graph.edges[3].src = 1;
graph.edges[3].dest = 3;
graph.edges[3].weight = 15;
graph.edges[4].src = 2;
graph.edges[4].dest = 3;
graph.edges[4].weight = 4;
graph.kruskalMST();
}
}
```
这个示例创建了一个具有4个顶点和5条边的图,并使用Kruskal算法找到最小生成树。输出结果将显示生成树的边及其对应的权重。你可以根据自己的需求修改顶点数、边数和具体的边权重。
阅读全文