0

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!

1 Answers1

1

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

kur ag
  • 591
  • 8
  • 19
  • Surprisingly for me, this solved the problem, indeed I should have added the edges in both directions to the graph, and it printed the correct path: 1 0 2 3 4, but not the correct distance. So this created two new questions to me: why do I have to add the edges in both directions, and why the distance is not correct, i.e. it prints the 60, instead of 140? –  Sep 09 '18 at 20:25
  • First question: Because your graph is undirected. You can look https://stackoverflow.com/questions/18613418/apply-dijkstras-algorithm-in-a-undirected-graph-with-negative-we. – kur ag Sep 09 '18 at 20:41