克鲁斯卡尔算法java
时间: 2023-10-26 18:20:11 浏览: 81
克鲁斯卡尔算法是一种用于求解最小生成树的算法,它的基本思路是将所有的边按照权值从小到大排序,然后依次选择权值最小的边,如果该边的两个端点不在同一个连通分量中,则将它们合并到同一个连通分量中,直到所有的点都在同一个连通分量中,此时就得到了最小生成树。
以下是克鲁斯卡尔算法的Java实现:
```java
import java.util.Arrays;
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 e = 0;
int i = 0;
for (i = 0; i < V; ++i) {
result[i] = new Edge();
}
Arrays.sort(edges);
int[] parent = new int[V];
Arrays.fill(parent, -1);
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; // Number of vertices in graph
int E = 5; // Number of edges in graph
Graph graph = new Graph(V, E);
// add edge 0-1
graph.edges[0].src = 0;
graph.edges[0].dest = 1;
graph.edges[0].weight = 10;
// add edge 0-2
graph.edges[1].src = 0;
graph.edges[1].dest = 2;
graph.edges[1].weight = 6;
// add edge 0-3
graph.edges[2].src = 0;
graph.edges[2].dest = 3;
graph.edges[2].weight = 5;
// add edge 1-3
graph.edges[3].src = 1;
graph.edges[3].dest = 3;
graph.edges[3].weight = 15;
// add edge 2-3
graph.edges[4].src = 2;
graph.edges[4].dest = 3;
graph.edges[4].weight = 4;
graph.kruskalMST();
}
}
```
以上代码实现了一个简单的图,包含四个顶点和五条边,可以根据实际情况修改。运行后输出最小生成树的边和总权值。
阅读全文
相关推荐



















