多源最短路徑弗洛伊德演算法(java)不含具體路徑
Floyd-Warshall演算法(Floyd-Warshall algorithm)是解決任意兩點間的最短路徑的一種演算法,可以正確處理有向圖或負權的最短路徑問題。
import java.util.Arrays;
public class Florid {
public int n =5;
public static void main(String[] args){
//鄰接矩陣
double a[][] = {{0.0,3.0,8.0,Double.MAX_VALUE,-4.0},
{Double.MAX_VALUE,0,Double.MAX_VALUE,1.0,7.0},
{Double.MAX_VALUE,4.0,0,Double.MAX_VALUE,Double.MAX_VALUE},
{2.0,Double.MAX_VALUE,-5.0,0.0,Double.MAX_VALUE},
{Double.MAX_VALUE,Double.MAX_VALUE,Double.MAX_VALUE,6.0,0.0}
};
Florid f = new Florid();
f.floridWarshall(a);
}
public void floridWarshall(double b[][]){
double a[][] = Arrays.copyOf(b, this.n);
//k代表加入的結點
//i代表新加入的點
for(int i=0;i<this.n;i++){
//j代表終點
for(int j=0;j<this.n;j++){
if(a[i][j]>a[i][k-1]+a[k-1][j]){
a[i][j] = a[i][k-1]+a[k-1][j];
}
}
}
}
//迴圈輸出各點間的最短距離
for(int m = 0;m<n;m++){
for(int s=0;s<n;s++){
System.out.print(a[m][s]+" ") ;
}
System.out.println();
}
}
}