最短路徑(弗洛伊德演算法)
阿新 • • 發佈:2019-02-04
1.定義概述
Floyd-Warshall演算法(Floyd-Warshall algorithm)是解決任意兩點間的最短路徑的一種演算法,可以正確處理有向圖或負權的最短路徑問題,同時也被用於計算有向圖的傳遞閉包。
2.例項演示
/**
* 弗洛伊德演算法求最短路徑
* @author sunbufu
*
*/
public class ShortestPathFloyd {
/**無窮大*/
final static int INF = Integer.MAX_VALUE;
public static void main(String[] args) {
int [] points = { 1, 2, 3, 4, 5, 6 };
int[][] weights = {
// 1 2 3 4 5 6
{0, 7, 9, INF, INF, 14 },//1
{7, 0, 10, 15, INF, INF },//2
{9, 10, 0, 11, INF, 2 },//3
{INF, 15, 11, 0, 6, INF },//4
{INF, INF, INF, 6, 0, 9 },//5
{14, INF, 2, INF, 9, 0 } //6
};
int[][] previousPoint = {
// 1 2 3 4 5 6
{1, 2, 3, 4, 5, 6 },//1
{1, 2, 3, 4, 5, 6 },//2
{1 , 2, 3, 4, 5, 6 },//3
{1, 2, 3, 4, 5, 6 },//4
{1, 2, 3, 4, 5, 6 },//5
{1, 2, 3, 4, 5, 6 } //6
};
floyd(points, weights, previousPoint);
}
private static void floyd(int[] points, int[][] weights, int[][] previousPoint) {
int pointsNumber = points.length;
for(int k = 0; k < pointsNumber; k ++){
for(int i = 0; i < pointsNumber; i ++){
for(int j = 0; j < pointsNumber; j ++){
if(weights[i][k] != INF && weights[k][j] != INF && (weights[i][k] + weights[k][j]) < weights[i][j]){
weights[i][j] = weights[i][k] + weights[k][j];
previousPoint[i][j] = k;
}
}
}
}
System.out.println(weights);
}
}
3.總結
簡潔的解決了最短路徑問題,但是時間複雜度為O(n^3)
。