public class prim {
static int M = 1000;
public static void main(String[] args) {
int graph[][] = { { M, 6, 1, 5, M, M }, { 6, M, 5, M, 3, M },
{ 1, 5, M, 5, 6, 4 }, { 5, M, 5, M, M, 2 },
{ M, 3, 6, M, M, 6 }, { M, M, 4, 2, 6, M } };
int start = 0;
int n = graph.length;
int[] visited = new int[n];
System.out.println(prim(graph, visited, start, n));
}
public static int prim(int[][] graph, int[] visited, int start, int n) {
int pos, result = 0;
int min = Integer.MAX_VALUE;
int[] low = new int[n];
// 从某点开始,分别标记和记录该点
visited[start] = 1;
pos = start;
System.out.print(pos + " ");
// 第一次给low数组赋值
for (int i = 0; i < n; i++)
if (i != pos)
low[i] = graph[pos][i];
// 再运行n-1次
for (int i = 0; i < n - 1; i++) {
// 找出最小权值并记录位置
min = Integer.MAX_VALUE;
for (int j = 0; j < n; j++)
if (visited[j] == 0 && min > low[j]) {
min = low[j];
pos = j;//记录最小值点
}
// 最短路径
result += min;
// 求出最小值后,设置为已经访问
visited[pos] = 1;
// 更新权值
for (int j = 0; j < n; j++)
if (visited[j] == 0 && low[j] > graph[pos][j])
low[j] = graph[pos][j];
System.out.print(pos + " ");
}
return result;
}
}
最小生成树prim
最新推荐文章于 2024-06-13 21:19:08 发布