思路:
依次取最短路径,如果可以两个顶点不是同一组则连接该路径直到所有顶点全都连接
代码:
package com.wangyq.datastructrue.arithmetic;
import java.util.Arrays;
public class Kruskal {
public static void main(String[] args) {
//构建图
int[][] ints = new int[7][7];
String[] names = new String[7];
names[0] = "A";
names[1] = "B";
names[2] = "C";
names[3] = "D";
names[4] = "E";
names[5] = "F";
names[6] = "G";
for (int[] ints1 : ints) {
for (int i = 0; i < ints1.length; i++) {
ints1[i] = Integer.MAX_VALUE;
}
}
ints[0][1] = 5;
ints[0][2] = 7;
ints[0][6] = 2;
ints[1][0] = 5;
ints[1][3] = 9;
ints[1][6] = 3;
ints[2][0] = 7;
ints[2][4] = 8;
ints[3][1] = 9;
ints[3][5] = 4;
ints[4][2] = 8;
ints[4][5] = 5;
ints[4][6] = 4;
ints[5][3] = 4;
ints[5][4] = 5;
ints[5][6] = 6;
ints[6][0] = 2;
ints[6][1] = 3;
ints[6][4] = 4;
ints[6][5] = 6;
//构建最小生成树
kruskal(ints,names);
}
private static void kruskal(int[][] ints,String[] names) {
int[] peaks = new int[ints.length];
for (int i = 0; i < ints.length; i++) {
peaks[i] = i;
}
int min = Integer.MAX_VALUE;
int tempK = 0;
int tempJ = 0;
//n个顶点有n-1条路
for (int i = 0; i < peaks.length - 1; i++) {
//重置最短路径
tempK = 0;
tempJ = 0;
min = Integer.MAX_VALUE;
//循环已经联通的顶点
for (int j = 0; j < peaks.length; j++) {
for (int k = 0; k < peaks.length; k++) {
/*
1.当前路径是通的
2.没有构成回路
3.路径比记录的小
*/
if (ints[j][k] < Integer.MAX_VALUE && peaks[k] != peaks[j] && ints[j][k] < min) {
min = ints[j][k];
tempK = k;
tempJ = j;
}
}
}
int tempInt = peaks[tempJ];
System.out.println("连接顶点"+names[tempJ]+"--"+names[tempK]);
//更新组
for (int j = 0; j < peaks.length; j++) {
if (peaks[j] == tempInt) {
peaks[j] = peaks[tempK];
}
}
}
}
}
运行结果:
连接顶点A–G
连接顶点B–G
连接顶点D–F
连接顶点E–G
连接顶点E–F
连接顶点A–C