一 背景
二 prim算法java版
package leaning.graph;
/*
* 最小生成树之普里姆算法
* */
public class PrimMiniCostSpanningTree {
//总权值
private int totalCounter = 0 ;
//总权值StringBuffer
private StringBuffer stringBuffer = new StringBuffer();
//计数器
private int counter =0;
//最大Int整数,表示无穷大
private int MAX_VALUE = Integer.MAX_VALUE;
//定义地图变量
private int map[][] = new int[9][9];
//定义节点
private String nodes[] = {"vo","v1","v2","v3","v4","v5","v6","v7","v8"};
//保存相关顶点边的权值
private int lowCost[] = new int[9];
//保存相关顶点下标
private int adjvex[] = new int[9];
public PrimMiniCostSpanningTree(){
this.init();
}
//初始化地图
public void initMap(){
this.map[0] = new int[]{ 0, 10,MAX_VALUE,MAX_VALUE,MAX_VALUE, 11,MAX_VALUE,MAX_VALUE,MAX_VALUE};
this.map[1] = new int[]{ 10, 0, 18,MAX_VALUE,MAX_VALUE,MAX_VALUE, 16,MAX_VALUE, 12};
this.map[2] = new int[]{MAX_VALUE,MAX_VALUE, 0, 22,MAX_VALUE,MAX_VALUE,MAX_VALUE,MAX_VALUE, 8};
this.map[3] = new int[]{MAX_VALUE,MAX_VALUE, 22, 0, 20,MAX_VALUE,MAX_VALUE, 16, 21};
this.map[4] = new int[]{MAX_VALUE,MAX_VALUE,MAX_VALUE, 20, 0, 26,MAX_VALUE, 7,MAX_VALUE};
this.map[5] = new int[]{ 11,MAX_VALUE,MAX_VALUE,MAX_VALUE, 26, 0, 17,MAX_VALUE,MAX_VALUE};
this.map[6] = new int[]{MAX_VALUE, 16,MAX_VALUE,MAX_VALUE,MAX_VALUE, 17, 0, 19,MAX_VALUE};
this.map[7] = new int[]{MAX_VALUE,MAX_VALUE,MAX_VALUE, 16, 7,MAX_VALUE, 19, 0,MAX_VALUE};
this.map[8] = new int[]{MAX_VALUE, 12, 8, 21,MAX_VALUE,MAX_VALUE,MAX_VALUE,MAX_VALUE, 0};
}
//初始化参数
public void init(){
//1 初始化地图
this.initMap();
//2 初始化lowCost和adjvex
for(int i = 0 ; i < this.lowCost.length ;i++){
this.lowCost[i] = 0;
this.adjvex[i] = 0;
}
}
// 普里姆算法核心
public void prim(){
// 1 取 v0 顶点,并为lowCost赋值
for(int i = 0 ; i < this.lowCost.length ;i++){
this.lowCost[i] = this.map[0][i];
}
for(int j = 1 ; j < this.lowCost.length ;j++){
// 2 从lowcost中计算得到最小权值
int min = MAX_VALUE;
int position = -1; //记录最小权值的位置
for(int i = 0 ; i < this.lowCost.length ;i++){
if( this.lowCost[i]!=0 && min > this.lowCost[i] ){
min = this.lowCost[i];
position = i;
}
}
// 3 得到最小值,并输出
this.counter++;
System.out.println("第 "+this.counter+" 条边为 : ["+this.nodes[this.adjvex[position]]+","+this.nodes[position]+"] = "+this.lowCost[position]+" ");
totalCounter = totalCounter + this.lowCost[position];
this.stringBuffer.append(this.lowCost[position]+"+");
// 4 调整adjvex和lowCost的值
this.lowCost[position] = 0;
this.adjvex[position] = 0;
for(int i = 0 ; i < this.lowCost.length ;i++){
if(this.map[position][i]!=0 && this.map[position][i]!=this.MAX_VALUE && this.lowCost[i]!=0 && this.lowCost[i] > this.map[position][i] ){
this.lowCost[i] = this.map[position][i];
this.adjvex[i] = position;
}
}
}
String result = this.stringBuffer.toString();
result = result.substring(0,result.length()-1);
System.out.println("总权值为 : " + result + " = " + this.totalCounter );
}
public static void main(String[] args) {
PrimMiniCostSpanningTree primMiniCostSpanningTree = new PrimMiniCostSpanningTree();
primMiniCostSpanningTree.prim();
}
}
三 运行结果图