简体   繁体   中英

Dijkstra Algorithm erroneous implementation for undirected graph

I am trying to implement the Dijkstra algorithm to find the shortest path from a starting vertex to every other vertex in an undirected weighted graph using this pseudocode:

Initialize D(v) = 0 and D(u) = ∞ for u != v
Initialize priority queue Q of vertices using D as key.
while Q is not empty do

u = Q.removeMin()
for each vertex z adjacent to u and in Q do

if  D(u) + w((u, z)) < D(z) then

    D(z) = D(u) + w((u, z))

    update z in Q

return D

from here: http://www.csl.mtu.edu/cs2321/www/newLectures/30_More_Dijkstra.htm

This is the implementation of it:

public void Dijkstra(int start) {
        int[] D = new int[E.length];
        for (int i = 0; i < E.length; i++) {
            D[i] = Integer.MAX_VALUE;
        }
        D[start] = 0;
        PriorityQueue<Integer> Q = new PriorityQueue<>();
        Q.add(start);
        while (!Q.isEmpty()) {
            Integer u = Q.poll();
            System.out.println(u + " ");
            for (int z = 0; z < E[u].size(); z++) {
                Edge e = E[u].get(z);
                if ((D[u] + e.w) < D[e.v]) {
                    D[e.v] = D[u] + e.w;
                    Q.add(e.v);
                }
            }
        }
        System.out.println(D[E.length - 1]);
    }

The graph is implemented using adjacency list, and here in the code D(u) the distance u is from v, E.length is the length of the adjacency list and w is the weight of an edge. For this example: 5 vertices, 6 edges, and pairs of vertices with the weight of the edge 0 1 20, 0 2 20, 0 4 40, 1 3 50, 2 3 30, and 3 4 70. The output, starting from 1 should be: 1 0 2 3 4, and the distance 140, but my implementation produces the output: 1 3 4, and the distance 120. My question is why I am getting this answer instead the right one with my implementation. If other parts of the class are needed I will post them. Thanks for reading and help!

I think you aren't looking all connections. For example, you have 0 1 edge, therefore you should add 1 0 edge to set.

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