Search code examples
javagraphqueuepriority-queuedijkstra

Why is the Dijkstra Implementation working even if I use Simple Queue instead of priority queue?


I tried implementing Dijkstra using normal queue and whenever I relax edge I add that vertex to the queue here is the implementation in java

import java.util.*;

public class Main 
{
    static HashMap<Integer, List<Edge>> graph = new HashMap<>();
    public static void main(String[] args)
    {
        graph.put(0, (List<Edge>)Arrays.asList(new Edge[]{
            new Edge(0, 1, 5),
            new Edge(0, 2, 2),
        }));
        graph.put(1, (List<Edge>)Arrays.asList(new Edge[]{
            new Edge(1, 3, 1),
        }));
        graph.put(2, (List<Edge>)Arrays.asList(new Edge[]{
            new Edge(2, 1, 1),
            new Edge(2, 3, 7),
        }));
        graph.put(3, (List<Edge>)Arrays.asList(new Edge[]{}));
        Integer[] dist = dijkstra(graph, graph.size(), 0);
        for(int i = 0;i < dist.length;i++)
        {
            System.out.print(" " + dist[i]);
        }
    }
    public static Integer[] dijkstra(HashMap<Integer, List<Edge>> graph, int numNodes, int start)
    {
        Integer[] dist = new Integer[numNodes];
        for(int i = 0; i < dist.length;i++)
        {
            dist[i] = Integer.MAX_VALUE;
        }

        LinkedList<Integer> queue = new LinkedList<Integer>();

        dist[start] = 0;
        queue.add(start);
        while(queue.size()!=0)
        {
            Integer current = queue.poll();
            List<Edge> edges = graph.get(current);
            for(Edge e : edges)
            {
                if(dist[e.from] + e.weight < dist[e.to])
                {
                    dist[e.to] = dist[e.from] + e.weight;
                    queue.add(e.to);
                }
            }
        }

        return dist;
    }
}

class Edge
{
    int from, to, weight;
    Edge(int from, int to, int weight)
    {
        this.from = from;
        this.to = to;
        this.weight = weight;
    }
}

as you can see i am adding vertex to queue whenever there is relaxation. My queustion is that is this correct Implementation, i mean will it work in all cases? and what drawbacks it has over priority queue?


Solution

  • Probably you should be good; not using a priority queue will only affect efficiency.

    Wikipedia:

    While the original algorithm uses a min-priority queue and runs in time Θ((V+E)logV) (where V is the number of nodes and E is the number of edges), it can also be implemented in Θ(V2) using an array.

    and

    Breadth-first search can be viewed as a special-case of Dijkstra's algorithm on unweighted graphs, where the priority queue degenerates into a FIFO queue.