I am applying the all-pairs shortest path algorithm (Floyd-Warshall) to this directed graph:
该图由其邻接矩阵表示。简单的代码如下所示:
public class ShortestPath {
public static void main(String[] args) {
int x = Integer.MAX_VALUE;
int [][] adj= {
{0, 6, x, 6, 7},
{x, 0, 5, x, x},
{x, x, 0, 9, 3},
{x, x, 9, 0, 7},
{x, 4, x, x, 0}};
int [][] D = adj;
for (int k=0; k<5; k++){
for (int i=0; i<5; i++){
for (int j=0; j<5; j++){
if(D[i][k] != x && D[k][j] != x && D[i][k]+D[k][j] < D[i][j]){
D[i][j] = D[i][k]+D[k][j];
}
}
}
}
//Print out the paths
for (int r=0; r<5; r++) {
for (int c=0; c<5; c++) {
if(D[r][c] == x){
System.out.print("n/a");
}else{
System.out.print(" " + D[r][c]);
}
}
System.out.println(" ");
}
}
}
就算法而言,上述效果很好。
我试图表明从任何节点到其自身的路径是not一定0
,正如此处使用邻接矩阵所暗示的那样,但可以是通过其他节点的任何可能的路径:例如B -...-...-...-B
有没有办法修改我当前的表示以表明最短路径,B
to B
,不为零,但是12
,遵循B-C-E-B
路线?可以通过某种方式修改邻接矩阵方法来完成吗?