所有结点对的最短路径问题
常量定义
private static final int NOT_A_VERTEX = -1;
算法实现
public static void allPairs(int[][] a, int[][] d, int[][] path) {
int n = a.length;
// Initialize d and path
for(int i = 0; i < n; i++) {
for(int j = 0; j < n; j++) {
d[i][j] = a[i][j];
path[i][j] = NOT_A_VERTEX;
}
}
for(int k = 0; k < n; k++) {
// Consider each vertex as an intermediate
for(int i = 0; i < n; i++) {
for(int j = 0; j < n; j++) {
if(d[i][k] + d[k][j] < d[i][j]) {
// Update shortest path
d[i][j] = d[i][k] + d[k][j];
path[i][j] = k;
}
}
}
}
}
说明
上面是计算所有结点对的最短路径的算法。
a[][] 包含邻接矩阵,其中 a[i][i] 假定为零。
d[] 包含最短路径的值。
顶点从0开始编号; 所有数组的维数相等。
如果 d[i][i] 设置为负值,则存在负周期。
实际路径可以使用 path[][] 进行计算。
完整代码
public class Main {
private static final int NOT_A_VERTEX = -1;
/**
* Compute all-shortest paths.
* a[][] contains the adjacency matrix with a[i][i] presumed to be zero.
* d[] contains the values of the shortest path.
* Vertices are numbered starting at 0; all arrays have equal dimension.
* A negative cycle exists if d[i][i] is set to a negative value.
* Actual path can be computed using path[][].
* NOT_A_VERTEX is -1
*/
public static void allPairs(int[][] a, int[][] d, int[][] path) {
int n = a.length;
// Initialize d and path
for(int i = 0; i < n; i++) {
for(int j = 0; j < n; j++) {
d[i][j] = a[i][j];
path[i][j] = NOT_A_VERTEX;
}
}
for(int k = 0; k < n; k++) {
// Consider each vertex as an intermediate
for(int i = 0; i < n; i++) {
for(int j = 0; j < n; j++) {
if(d[i][k] + d[k][j] < d[i][j]) {
// Update shortest path
d[i][j] = d[i][k] + d[k][j];
path[i][j] = k;
}
}
}
}
}
public static void main(String[] args) {
int[][] a = { { 0, 2, -2, 2 }, { 1000, 0, -3, 1000 }, { 4, 1000, 0, 1000 }, { 1000, -2, 3, 0 } };
int[][] d = new int[4][4];
int[][] path = new int[4][4];
allPairs(a, d, path);
for(int i = 0; i < 4; i++) {
for(int j = 0; j < 4; j++) {
System.out.print(d[i][j] + "\t");
}
System.out.println();
}
for(int i = 0; i < 4; i++) {
for(int j = 0; j < 4; j++) {
System.out.print(path[i][j] + "\t");
}
System.out.println();
}
}
}
测试结果
0 0 -3 2
1 0 -3 3
4 4 0 6
-1 -2 -5 0
-1 3 3 -1
2 -1 -1 2
-1 3 -1 0
2 -1 1 -1