最小生成树,简称MST。
求最小生成树的算法主要是普里姆算法和克鲁斯卡尔算法。
public class PrimAlgorithm {
public static void main(String[] args) {
// 测试
char[] data = new char[]{'A', 'B', 'C', 'D', 'E', 'F', 'G'};
int verxs = data.length;
int[][] weight = new int[][]{
{10000,5,7,10000,10000,10000,2},
{5,10000,10000,9,10000,10000,3},
{7,10000,10000,10000,8,10000,10000},
{10000,9,10000,10000,10000,4,10000},
{10000,10000,8,10000,10000,5,4},
{10000,10000,10000,4,5,10000,6},
{2,3,10000,10000,4,6,10000}
};
MGraph graph = new MGraph(verxs);
MinTree minTree = new MinTree();
minTree.createGraph(graph, verxs, data, weight);
minTree.showGraph(graph);
minTree.prim(graph,0);
}
}
// 创建最小生成树
class MinTree {
/**
* 创建图的邻接矩阵
*
* @param graph 图对象
* @param verxs 图对应的顶点个数
* @param data 图的各个顶点的值
* @param weight 图的邻接矩阵
*/
public void createGraph(MGraph graph, int verxs, char[] data, int[][] weight) {
int i, j;
for (i = 0; i < verxs; i++) {
graph.data[i] = data[i];
for (j = 0; j < verxs; j++) {
graph.weight[i][j] = weight[i][j];
}
}
}
/**
* 显示图的邻接矩阵
*
* @param graph 图对象
*/
public void showGraph(MGraph graph) {
for (int[] link : graph.weight) {
System.out.println(Arrays.toString(link));
}
}
/**
* 编写 prim 算法,得到最小生成树
*
* @param graph 图对象
* @param v 表示从图的第几个顶点开始生成
*/
public void prim(MGraph graph, int v) {
// visited 标记点是否被访问过
int[] visited = new int[graph.verxs];
// 把当前这个节点标记为已访问
visited[v] = 1;
// h1 和 h2 记录两个顶点的下标
int h1 = -1;
int h2 = -1;
int minWeight = 10000; // 将 minWeight 初始为一个大数,后面遍历的过程中,会被替换
for (int k = 1; k < graph.verxs; k++) { // 因为有 graph.verxs 顶点,普里姆算法结束后,有 graph.verxs - 1 个边
// 这个是确定每一次生成的子图,和哪个节点的距离最近
for (int i = 0; i < graph.verxs; i++) { // i 节点表示被访问过的节点
for (int j = 0; j < graph.verxs; j++) { // j 节点表示还没有被访问过的节点
if(visited[i] == 1 && visited[j] == 0 && graph.weight[i][j] < minWeight){
// 替换 minWeight (寻找已经访问的节点和未访问的节点间的权值最小的边)
minWeight = graph.weight[i][j];
h1 = i;
h2 = j;
}
}
}
// 找到一条边是最小
System.out.println("边<" + graph.data[h1] + "," + graph.data[h2] + ">权值:" + minWeight);
// 将当前找到的节点标记为已经访问
visited[h2] = 1;
// 重新将 minWeight 设置为最大值
minWeight = 10000;
}
}
}
class MGraph {
int verxs; // 表示图的节点的个数
char[] data; // 存放节点数据
int[][] weight; // 存放边,就是我们的邻接矩阵
public MGraph(int verxs) {
this.verxs = verxs;
this.data = new char[verxs];
this.weight = new int[verxs][verxs];
}
}