上一篇博客(【算法】最小生成树—Prim算法与Kruskal算法),我们了解到了Prim算法与Kruskal算法含义以及区别。Prim算法和Kruskal算法都是解决最小生成树问题的经典算法。那么Prim算法和Kruskal算法该如何实现呢?
1、Prim算法Java代码实现的案例
import java.util.Arrays;
public class PrimAlgorithm {
public static int[] prim(int[][] graph, int startNode) {
int n = graph.length;
boolean[] visited = new boolean[n];
int[] parent = new int[n];
int[] key = new int[n];
// Initializing keys to infinite and keys of this node to 0
Arrays.fill(key, Integer.MAX_VALUE);
key[startNode] = 0;
// Do n-1 times to get n vertices
for (int i = 0; i < n - 1; i++) {
int min = Integer.MAX_VALUE, minIndex = -1;
for (int j = 0; j < n; j++) {
if (!visited[j] && key[j] < min) {
min = key[j];
minIndex = j;
}
}
if (minIndex == -1) {
// There is no connected graph
return null;
}
visited[minIndex] = true;
// Updating keys of vertices
for (int j = 0; j < n; j++) {
if (!visited[j] && graph[minIndex][j] != 0 && (key[j] > graph[minIndex][j])) {
parent[j] = minIndex;
key[j] = graph[minIndex][j];
}
}
}
// Storing path
int[] path = new int[n];
for (int i = 0; i < n; i++) {
int k = i;
while (parent[k] != -1) {
path[i] += key[k];
k = parent[k];
}
}
return path;
}
public static void main(String[] args) {
int[][] graph = {
{0, 2, 0, 6, 0},
{2, 0, 3, 8, 5},
{0, 3, 0, 0, 7},
{6, 8, 0, 0, 9},
{0, 5, 7, 9, 0}
};
int[] primTree = prim(graph, 0);
if (primTree != null) {
for (int cost : primTree) {
System.out.print(cost + " ");
}
} else {
System.out.println("No connected graph");
}
}
}
2、Kruskal算法Java代码实现的案例
import java.util.Arrays;
import java.util.Comparator;
public class KruskalAlgorithm {
static class Edge implements Comparable<Edge> {
int start;
int end;
int weight;
Edge(int start, int end, int weight) {
this.start = start;
this.end = end;
this.weight = weight;
}
@Override
public int compareTo(Edge other) {
return this.weight - other.weight;
}
}
public static int[] kruskal(int n, Edge[] edges) {
int[] parent = new int[n];
for (int i = 0; i < n; i++) {
parent[i] = i;
}
int[] result = new int[n - 1];
int e = 0;
Arrays.sort(edges);
for (Edge edge : edges) {
int x = edge.start;
int y = edge.end;
int rootX = findParent(parent, x);
int rootY = findParent(parent, y);
if (rootX != rootY) {
parent[rootX] = rootY;
result[e++] = edge.weight;
}
}
return result;
}
private static int findParent(int[] parent, int i) {
if (parent[i] == i) {
return i;
}
return parent[i] = findParent(parent, parent[i]);
}
public static void main(String[] args) {
int n = 5; // 节点数
Edge[] edges = {
new Edge(1, 0, 7),
new Edge(0, 2, 8),
new Edge(2, 1, 9),
new Edge(0, 3, 5),
new Edge(3, 4, 3),
new Edge(1, 4, 7),
new Edge(2, 4, 6)
};
int[] kruskalMST = kruskal(n, edges);
for (int weight : kruskalMST) {
System.out.println(weight);
}
}
}