-1

My implementation for directed graph works fine. It's a "lazy" version because it uses simple priority queues instead of indexed ones. I changed the code to get a solution for undirected graphs but it doesn't work. dijkstra(int s) is a method of a class Graph. The implementation of Graph is based on a list of adjacencies. The entire code is based on the explanations of Sedgewick's book.

public void dijkstra(int s) {

    marked = new boolean[V];
    distTo = new int[V];
    edgeTo = new Edge[V];

    Comparator<Edge> comparator = new Comparator<Edge>() {

        public int compare(Edge e1, Edge e2) {

            int dist1 = distTo[e1.either()] + e1.weight();
            int dist2 = distTo[e2.either()] + e2.weight();

            if (dist1 < dist2) {
                return -1;
            } else if (dist1 > dist2) {
                return 1;
            } else {
                return  0;
            }
        }
    };

    pq = new PriorityQueue<Edge>(comparator);

    for (int v = 0; v < V; ++v) {
        distTo[v] = Integer.MAX_VALUE;
    }

    distTo[s] = 0;

    relax(s);

    while (!pq.isEmpty()) {

        Edge e = pq.poll();

        int v = e.either();
        int w = e.other(v);

        if (!marked[w]) {
            relax(w);
        }
    }
}

private void relax(int v) {

    marked[v] = true;

    for (Edge e : adj[v]) {

        int w = e.other(v);

        if (distTo[w] > distTo[v] + e.weight()) {

            distTo[w] = distTo[v] + e.weight();
            edgeTo[w] = e;
            pq.add(e);
        }
    }
}
  • 1
    "Doesn't work" ? Be more specific if you want people to be able to help. – Erwin Bolwidt Jun 27 '16 at 06:58
  • 1
    Could you please explain what do you mean by "it does not work"? It would be good that you tried to produce a [reproducible example](http://stackoverflow.com/help/mcve). Thanks. – lrnzcig Jun 27 '16 at 06:59
  • The dijkstra's algorithm should provide the shortest path. My implementation provides a possible path, but not the shortest one. – Fabio Cassinelli Jun 27 '16 at 07:09
  • I would suggest you to first debug your code in a standard IDE using breakpoints. It will be easier to trace the flow and hence you will know why you are unable to get the correct output. – Mrunal Pagnis Jun 27 '16 at 07:32
  • Please show the specific instance on which a shortest path is not found by the implementation. – Codor Jun 28 '16 at 09:32
  • I solved it. I edited my question with the "solution" to the problem. – Fabio Cassinelli Jun 28 '16 at 11:54
  • @FabioCassinelli - Solutions to questions should be added as answers and marked as resolved if it correctly answers the question. – Shubham Mittal Aug 23 '16 at 19:08

1 Answers1

0

I solved it. Stupid mistake. Instead of adding the edges

v->w and w->v

I added the edges

v->w and w->w

i.e. I added the same edge twice, without creating the reverse edge.