Java实现普里姆算法
本实例的图基于邻接矩阵
图类:
package prim;
public class Graph {
final int max=100;
/*
* 顶点节点
*/
public class VexNode{
int adjvex;
int data;
}
VexNode[] vexNodes;
int[] thevexs; //顶点集合
int[][] edges = new int[max][max]; //边集合
/*
* 创建图
*/
public void createGraph(Graph graph,int[][] A,int[] vexs) {
thevexs=vexs;
for (int i = 0; i < vexs.length; i++) {
for (int j = 0; j < vexs.length; j++) {
graph.edges[i][j] = A[i][j];
}
}
}
/*
* 输出图
*/
public void printGraph(Graph graph) {
for (int i = 0; i < graph.thevexs.length; i++) {
for (int j = 0; j < graph.thevexs.length; j++) {
//没有路径则输出/
if (graph.edges[i][j]==-1) {
System.out.printf("%4s","/");
}else {
System.out.printf("%4d",graph.edges[i][j]);
}
}
System.out.println("\n");
}
}
}
Prim算法:
package prim;
public class Prim {
final int max=100;
int[] lowcost = new int[max];
int[] closest = new int[max];
int min=10;
int k;
int num;
public Prim(Graph graph,int v) {
for (int i = 0; i < graph.thevexs.length; i++) {
lowcost[i] = graph.edges[v][i];
closest[i] = v;
}
for(int i=1;i<graph.thevexs.length;i++) {
k=-1;
min=10;
for(int j=0;j<graph.thevexs.length;j++) {
if (lowcost[j]>0&&lowcost[j]<min) {
min=lowcost[j];
k=j;
}
}
System.out.printf("(%d,%d),权值为:%d",closest[k],k,min);
System.out.println("\n");
num=num+min;
lowcost[k] = 0;
for (int p = 0; p < graph.thevexs.length; p++) {
if (graph.edges[k][p]>0&&graph.edges[k][p]<lowcost[p]) {
lowcost[p] = graph.edges[k][p];
closest[p] = k;
}
}
}
System.out.println("最短路径长度为:"+num);
}
}
测试:
package prim;
public class Test {
public static void main(String[] args) {
int[] vexs = {0,1,2,3,4};
int[][] A = {
{0,1,3,4,7},
{1,0,2,-1,-1},
{3,2,0,5,8},
{4,-1,5,0,6},
{7,-1,8,6,0}
};
Graph graph = new Graph();
graph.createGraph(graph, A, vexs);
graph.printGraph(graph);
Prim prim = new Prim(graph, 0);
}
}