您的位置:首页 > 其它

每对顶点的最短路径 : 基本算法

2013-08-29 10:39 519 查看
public class AllPairsShortestPaths {

static final int M = 10000; //unreachable

//extend-shortest-path
static int[][] extendShortestPath(int[][] L, int[][] W) {
int[][] R = new int[L.length][L[0].length];
int n = L.length;
for(int i = 0; i <  n; i++) {
for(int j = 0; j <  n; j++) {
R[i][j] = M;
for(int k = 0; k < n; k++) {
if(R[i][j] > (L[i][k] + W[k][j]))
R[i][j] = L[i][k] + W[k][j];
}
}
}
return R;
}

//slow-all-pairs-shortest-paths
static void slowAllPairsShortestPaths(int[][] W) {
int n = W.length;
/*
* D1 = W
* max n - 1 edges
* L(n-1) == L(n) == L(n + 1)
*/
int[][] L = W;
for(int i = 2; i < n; i++) {
L = extendShortestPath(L, W);
}

//print
for(int i = 0; i < n; i++) {
for(int j = 0; j < n; j++) {
System.out.printf("%c -> %c (%d) : \n", (char)('A' + i), (char)('A' + j), L[i][j]);
}
System.out.println();
}
System.out.println();
}

//faster-all-pairs-shortest-paths
static void fasterAllPairsShortestPaths(int[][] W) {
int n = W.length;
/*
* D1 = W
* L(n-1) == L(n) == L(n + 1)
*/
int[][] L = W;
int m = 1;
while(m < n) {
L = extendShortestPath(L, W);
m = 2 * m;
}

//print
for(int i = 0; i < n; i++) {
for(int j = 0; j < n; j++) {
System.out.printf("%c -> %c (%d) : \n", (char)('A' + i), (char)('A' + j), L[i][j]);
}
System.out.println();
}
System.out.println();
}

public static void main(String[] args) {
int[][] edges = {
{0, 3, 8, M, -4},
{M, 0, M, 1, 7},
{M, 4, 0, M, M},
{2, M, -5, 0, M},
{M, M, M, 6, 0}
};

System.out.println("slow-all-pairs-shortest-paths");
slowAllPairsShortestPaths(edges);

System.out.println("faster-all-pairs-shortest-paths");
fasterAllPairsShortestPaths(edges);
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息