Java实现普里姆算法

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);
		
	}

}
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值