简体   繁体   中英

Dijkstra's Algorithm Assistance

Given an adjacency matrix, I need to compute the shortest path between the first vertex and the last vertex (generally, vertex i and j, but we can ignore that for the time being). I've written an algorithm that really only correctly computes the distance between the first and second node (a step in the right direction, I guess).

static int dijkstra(int[][] G, int i, int j) {
    //Get the number of vertices in G
    int n = G.length;
    int[] bestpath = new int[n];
    int max = Integer.MAX_VALUE;
    boolean[] visited = new boolean[n];

    for (int x = 0; x < n; x++) {
        visited[x] = false;
        bestpath[x] = max;
    }

    bestpath[i] = 0;

    for (int x = 0; x < n; x++) {
        int min = max;
        int currentNode = i;
        for (int y = 0; y < n; y++) {
            if (!visited[y] && bestpath[y] < min) {
                System.out.println(G[y][x]);
                currentNode = y;
                min = bestpath[y];
            }
        }
        visited[currentNode] = true;
        for (int y = 0; y < n; y++) {
            if (G[currentNode][y] < max && bestpath[currentNode] + G[currentNode][y] < bestpath[y]) {
                bestpath[y] = bestpath[currentNode] + G[currentNode][y];
            }
        }
    }

    return bestpath[j];
}

If I were to guess, I'd say my logic is flawed in this section:

 for (int y = 0; y < n; y++) {
            if (!visited[y] && bestpath[y] < min) {
                System.out.println(G[y][x]);
                currentNode = y;
                min = bestpath[y];
            }
 }

An example would be the matrix

0 1 0 
1 0 1
0 1 0 

which would return 2 (one path between vertex one and two of weight 1 and another between 2 and 3 with weight 1).

If the matrix is not just storing 1s and 0s, but the distance from i to j, then you really need to keep track of the best distance from any node i to j. In other words, your working array should be a working matrix instead. Even if you are just doing a non - weighted graph, I think this approach is better.

There are different versions of the SPF algorithm. Post pseudocode for what you are trying to translate into java.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM