弗洛伊德算法--最短路径

算法如下:

import java.util.Scanner;


public class Floyd {


	public static void main(String[] args) {
//      测试数据	    
//		9 16
//		0 1 1
//		0 2 5
//		1 3 7
//		1 4 5
//		2 4 1
//		2 5 7
//		1 2 3
//		3 4 2
//		4 5 3
//		3 6 3
//		4 6 6
//		4 7 9
//		5 7 5
//		6 7 2
//		6 8 7
//		7 8 4
		Scanner scan = new Scanner(System.in);
	    int m = scan.nextInt();
	    int edges = scan.nextInt();
        int[][] arr = new int[m][m];
        for(int i =0;i<m;i++){
        	for(int j=0;j<m;j++){
        		if(i==j){
        			arr[i][j]=0;
        		}else{
        			arr[i][j]=65535;
        		}   		
        	}
        }
        int begin,end,weight;
        for(int i=0;i<edges;i++){
        	begin=scan.nextInt();
        	end=scan.nextInt();
        	weight=scan.nextInt();
        	arr[begin][end] = weight;
        	arr[end][begin] = weight;
        }
        //测试0到8
        shortestPath_Floyd(arr,0,8);
	}

	public static void shortestPath_Floyd(int[][] arr,int begin,int end){
		int[][] pathMatirx = new int[arr.length][arr.length] ;
		int[][] shortPathTable = new int[arr.length][arr.length];
		for(int v=0;v<arr.length;v++){
			for(int w=0;w<arr.length;w++){
				shortPathTable[v][w]=arr[v][w];
				pathMatirx[v][w]=w;
			}
		}
		
		for(int k=0;k<arr.length;k++){
			for(int v=0;v<arr.length;v++){
				for(int w=0;w<arr.length;w++){
					if(shortPathTable[v][w]>shortPathTable[v][k]+shortPathTable[k][w]){
						shortPathTable[v][w]=shortPathTable[v][k]+shortPathTable[k][w];
						pathMatirx[v][w] = pathMatirx[v][k];
					}
				}
			}
		}
		int mark;
		System.out.println("begin:"+begin+" "+"end:"+end+" "+"weight:"+shortPathTable[begin][end]);
		mark = pathMatirx[begin][end];
		System.out.print(begin);
		while(mark!=end){
			System.out.print("-->"+mark);
			mark=pathMatirx[mark][end];
		}
		System.out.println("-->"+end);
	}
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值