普里姆算法介绍
普利姆(Prim)算法求最小生成树,也就是在包含n个顶点的连通图中,找出只有(n-1)条边包含所有n个顶点的连通子图,也就是所谓的极小连通子图
普利姆的算法如下:
设G=(V,E)是连通网,T=(U,D)是最小生成树,V,U是顶点集合,E,D是边的集合
若从顶点u开始构造最小生成树,则从集合V中取出顶点u放入集合U中,标记顶点v的visited[u]=1
若集合U中顶点ui与集合V-U中的顶点vj之间存在边,则寻找这些边中权值最小的边,但不能构成回路,将顶点vj加入集合U中,将边(ui,vj)加入集合D中,标记visited[vj]=1
重复步骤②,直到U与V相等,即所有顶点都被标记为访问过,此时D中有n-1条边
提示: 单独看步骤很难理解,我们通过代码来讲解,比较好理解.
public class PrimAlgorithm {
public static void main(String[] args) {
char[] data = {'A', 'B', 'C', 'D', 'E', 'F', 'G'};
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},};
int verxs = data.length;
Graph graph = new Graph(verxs, data, weight);
graph.show();
graph.prim(0);
}
}
class Graph {
int verxs;
char[] data;
int[][] weight;
public Graph(int verxs, char[] data, int[][] weight) {
this.verxs = verxs;
this.data = data;
this.weight = weight;
}
public void show() {
for (int i = 0; i < weight.length; i++) {
System.out.println(Arrays.toString(weight[i]));
}
}
public void prim(int v) {
int[] visited = new int[verxs];
int h1 = -1;
int h2 = -1;
int minWeight = 10000;
visited[v] = 1;
// 有verxs个顶点,prim算法结束后有verxs-1条边,所以从1开始
for (int i = 1; i < verxs; i++) {
// j表示已经访问的节点
for (int j = 0; j < verxs; j++) {
// k表示未访问的节点
for (int k = 0; k < verxs; k++) {
// 寻找已访问和未访问节点之间权值最小的边
if (visited[j] == 1 && visited[k] == 0 && weight[j][k] < minWeight) {
minWeight = weight[j][k];
h1 = j;
h2 = k;
}
}
}
// 找到一条边最小
System.out.println("<" + data[h1] + "," + data[h2] + ">" + ",weight=" + weight[h1][h2]);
visited[h2] = 1;
minWeight = 10000;
}
}
}