求最小生成树Java
时间: 2023-07-22 13:11:13 浏览: 49
下面是Java实现的Kruskal算法求最小生成树的代码:
```java
import java.util.*;
class Edge {
int src, dest, weight;
public Edge(int src, int dest, int weight) {
this.src = src;
this.dest = dest;
this.weight = weight;
}
}
class Graph {
int V, E;
Edge[] edges;
public Graph(int V, int E) {
this.V = V;
this.E = E;
edges = new Edge[E];
for (int i = 0; i < E; i++) {
edges[i] = new Edge(0, 0, 0);
}
}
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 e = 0;
Arrays.sort(edges, Comparator.comparingInt(o -> o.weight));
int[] parent = new int[V];
Arrays.fill(parent, -1);
int i = 0;
while (e < V - 1) {
Edge next_edge = edges[i++];
int x = find(parent, next_edge.src);
int y = find(parent, next_edge.dest);
if (x != y) {
result[e++] = next_edge;
union(parent, x, y);
}
}
System.out.println("Following are the edges in the constructed MST");
int minimumCost = 0;
for (i = 0; i < e; ++i) {
System.out.println(result[i].src + " -- " + result[i].dest + " == " + result[i].weight);
minimumCost += result[i].weight;
}
System.out.println("Minimum Cost Spanning Tree : " + minimumCost);
}
}
public class Main {
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();
}
}
```
这段代码使用了Kruskal算法求解最小生成树,具体实现逻辑可以看注释。