Modification of shortest path algorithm (route from a node to itself)

☆樱花仙子☆ 提交于 2019-12-22 08:35:36

问题


I am applying the all-pairs shortest path algorithm (Floyd-Warshall) to this directed graph:

The graph is represented by its adjacency matrix. The simple code looks like this:

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(" ");
     }
}

}

The above works fine as far as the algorithm is concerned.

I am trying to indicate that a path from any node to itself is not necessarily 0, as implied by the use of the adjacency matrix here, but can be any possible path through other nodes: For example B -...-...-...-B

Is there a way to modify my current representation to indicate that a shortest path from say, B to B, is not zero, but 12, following the B-C-E-B route? Can it be done by somehow modifying the adjacency matrix method?


回答1:


Changing the diagonal elements adjacency matrix from 0 to infinity (theoretically) should work.

It means the self loop cost is infinite and any other path with less than this cost is better hence if a path exists from a node to itself, through other nodes, its cost will be finite and it will replace the infinite value.

Practically you can use maximum value of integer as infinite.



来源:https://stackoverflow.com/questions/1954743/modification-of-shortest-path-algorithm-route-from-a-node-to-itself

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!