最小生成树
在一给定的无向图G = (V, E) 中,(u, v) 代表连接顶点 u 与顶点 v 的边,而 w(u, v) 代表此边的权重,若存在 T 为 E 的子集,使得 w(T) 最小,则此 T 为 G 的最小生成树。最小生成树可以用kruskal(克鲁斯卡尔)算法或prim(普里姆)算法求出。
Prim算法
普利姆算法(Prim)求的是最小生成树,也就是在包含n个顶点的无向连通图中找到(n-1)条边包含所有n个顶点的连通子图。
代码
/*无向连通图*/
public class Graph {
int vertexs;
char[] data;
int[][] weight;
public Graph(int vertexs,char[] data,int[][] weight){
this.vertexs = vertexs;
this.data = new char[vertexs];
this.weight = new int[vertexs][vertexs];
for (int i = 0; i < vertexs; i++) {
this.data[i] = data[i];
for (int j = 0; j < vertexs; j++) {
this.weight[i][j] = weight[i][j];
}
}
}
}
public class Prim {
public static void main(String[] args) {
char[] data = {'A','B','C','D','E','F','G'};
/*0表示两个顶点之间不能直接到达*/
int[][] weight = {{0,5,7,0,0,0,2},
{5,0,0,9,0,0,3},
{7,0,0,0,8,0,0},
{0,9,0,0,0,4,0},
{0,0,8,0,0,5,4},
{0,0,0,4,5,0,6},
{2,3,0,0,4,6,0}};
/*初始化图*/
Graph graph = new Graph(data.length,data,weight);
prim(graph,0);
}
/**
* prim算法求最小生成树
* @param graph 带权连通图
* @param v 从哪个顶点开始生成
*/
public static void prim(Graph graph,int v){
/*标记顶点是否被访问*/
boolean[] isVisited = new boolean[graph.vertexs];
/*标记当前顶点已经被访问*/
isVisited[v] = true;
/*h1,h2记录两个顶点下标*/
int h1 = -1;
int h2 = -1;
int miniWeight = 10000;
for (int i = 1; i < graph.vertexs; i++) { //因为有vertexs个顶点 根据prim算法会生成vertexs-1条边 所以i从1开始
for (int j = 0; j < graph.vertexs; j++) { //遍历已经访问过的顶点 例如图中的<A,G>
for (int k = 0; k < graph.vertexs; k++) { //遍历未访问过的顶点 例如图中的A-C[7],A-B[5],G-B[3],G-E[4],G-F[6]
if (isVisited[j] && !isVisited[k] &&graph.weight[j][k] > 0 && graph.weight[j][k] < miniWeight){
miniWeight = graph.weight[j][k];
h1 = j;
h2 = k;
}
}
}
System.out.println(graph.data[h1]+"->"+graph.data[h2]+"权值:"+miniWeight);
isVisited[h2] = true;
miniWeight = 10000;
}
}
}
运行结果
A->G权值:2
G->B权值:3
G->E权值:4
E->F权值:5
F->D权值:4
A->C权值:7
Process finished with exit code 0