假设现在有一个用邻接表实现的图,顶点数为V,请你给出java版的prim算法代码
时间: 2024-05-03 08:20:37 浏览: 111
下面给出java版的prim算法代码,用于在邻接表中计算最小生成树:
```java
import java.util.*;
class Graph {
static class Edge {
int src, dest, weight;
Edge() {
src = dest = weight = 0;
}
}
static class Subset {
int parent, rank;
}
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(Subset[] subsets, int i) {
if (subsets[i].parent != i)
subsets[i].parent = find(subsets, subsets[i].parent);
return subsets[i].parent;
}
void Union(Subset[] subsets, int x, int y) {
int xroot = find(subsets, x);
int yroot = find(subsets, y);
if (subsets[xroot].rank < subsets[yroot].rank)
subsets[xroot].parent = yroot;
else if (subsets[xroot].rank > subsets[yroot].rank)
subsets[yroot].parent = xroot;
else {
subsets[yroot].parent = xroot;
subsets[xroot].rank++;
}
}
void primMST() {
Edge[] result = new Edge[V];
int i;
for (i = 0; i < V; ++i)
result[i] = new Edge();
Arrays.sort(edges, (a, b) -> a.weight - b.weight);
Subset[] subsets = new Subset[V];
for (i = 0; i < V; ++i)
subsets[i] = new Subset();
for (int v = 0; v < V; ++v) {
subsets[v].parent = v;
subsets[v].rank = 0;
}
i = 0;
while (i < V - 1) {
Edge next_edge = edges[i++];
int x = find(subsets, next_edge.src);
int y = find(subsets, next_edge.dest);
if (x != y) {
result[i - 1] = next_edge;
Union(subsets, x, y);
}
}
System.out.println("\nFollowing are the edges in " + "the constructed MST");
int minimumCost = 0;
for (i = 0; i < V - 1; ++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 PrimAlgorithm {
public static void main(String[] args) {
int V = 5; // Number of vertices in graph
int E = 7; // 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 = 2;
// add edge 0-2
graph.edges[1].src = 0;
graph.edges[1].dest = 2;
graph.edges[1].weight = 1;
// add edge 0-3
graph.edges[2].src = 0;
graph.edges[2].dest = 3;
graph.edges[2].weight = 3;
// add edge 1-3
graph.edges[3].src = 1;
graph.edges[3].dest = 3;
graph.edges[3].weight = 4;
// add edge 2-4
graph.edges[4].src = 2;
graph.edges[4].dest = 4;
graph.edges[4].weight = 5;
// add edge 3-4
graph.edges[5].src = 3;
graph.edges[5].dest = 4;
graph.edges[5].weight = 7;
// add edge 1-2
graph.edges[6].src = 1;
graph.edges[6].dest = 2;
graph.edges[6].weight = 6;
graph.primMST();
}
}
```
以上代码是用java实现的prim算法的邻接表版本。
阅读全文