Dijkstra's shortest path algorithm in Java using PriorityQueue - GeeksforGeeks

28 Jan, 2022
Dijkstra’s algorithm is very similar to Prim’s algorithm for minimum spanning tree. Like Prim’s MST, we generate a SPT (shortest path tree) with a given source as a root. We maintain two sets, one set contains vertices included in the shortest-path tree, other set includes vertices not yet included in the shortest-path tree. At every step of the algorithm, we find a vertex that is in the other set (set of not yet included) and has a minimum distance from the source. 
Here the only drawback with Dijkstra algorithms is that while finding the shortest path as listed as follows as we need to find the least cost path by going through the whole cost array. Not a big deal for small graphs and at the same time becomes an efficiency issue for large graphs because each time we need to run through an array while traversing. Now as we know queues can work for us so do we apply the concept of priority queues with this algorithm to erupt out some of the disadvantages and making complexity much better.
Let us now discuss the problem statement whereas in accordance with the title it seems like the sheer implementation of one of the data structures known as priority queue with involvement of algorithm analysis in it. So let us begin with the problem statement which is listed below prior to it do stress over note as the whole concept revolves around the adjacency matrix representation.
Note: Dijkstra’s shortest Path implementations like Dijkstra’s Algorithm for Adjacency Matrix Representation (With time complexity O(v2)
Problem statement
Given a graph with adjacency list representation of the edges between the nodes, the task is to implement Dijkstra’s Algorithm for single-source shortest path using Priority Queue in Java. Given a graph and a source vertex in the graph, find the shortest paths from the source to all vertices in the given graph.
Illustration:
Input  : Source = 0
Output : 
     Vertex   Distance from Source
        0                0
        1                4
        2                12
        3                19
        4                21
        5                11
        6                9
        7                8
        8                14
Implementation:
Java
// Java Program to Implement Dijkstra's Algorithm// Using Priority Queue // Importing utility classesimport java.util.*; // Main class DPQpublic class GFG {     // Member variables of this class    private int dist[];    private Set<Integer> settled;    private PriorityQueue<Node> pq;    // Number of vertices    private int V;    List<List<Node> > adj;     // Constructor of this class    public GFG(int V)    {         // This keyword refers to current object itself        this.V = V;        dist = new int[V];        settled = new HashSet<Integer>();        pq = new PriorityQueue<Node>(V, new Node());    }     // Method 1    // Dijkstra's Algorithm    public void dijkstra(List<List<Node> > adj, int src)    {        this.adj = adj;         for (int i = 0; i < V; i++)            dist[i] = Integer.MAX_VALUE;         // Add source node to the priority queue        pq.add(new Node(src, 0));         // Distance to the source is 0        dist[src] = 0;         while (settled.size() != V) {             // Terminating condition check when            // the priority queue is empty, return            if (pq.isEmpty())                return;             // Removing the minimum distance node            // from the priority queue            int u = pq.remove().node;             // Adding the node whose distance is            // finalized            if (settled.contains(u))                 // Continue keyword skips exwcution for                // following check                continue;             // We don't have to call e_Neighbors(u)            // if u is already present in the settled set.            settled.add(u);             e_Neighbours(u);        }    }     // Method 2    // To process all the neighbours    // of the passed node    private void e_Neighbours(int u)    {         int edgeDistance = -1;        int newDistance = -1;         // All the neighbors of v        for (int i = 0; i < adj.get(u).size(); i++) {            Node v = adj.get(u).get(i);             // If current node hasn't already been processed            if (!settled.contains(v.node)) {                edgeDistance = v.cost;                newDistance = dist[u] + edgeDistance;                 // If new distance is cheaper in cost                if (newDistance < dist[v.node])                    dist[v.node] = newDistance;                 // Add the current node to the queue                pq.add(new Node(v.node, dist[v.node]));            }        }    }     // Main driver method    public static void main(String arg[])    {         int V = 5;        int source = 0;         // Adjacency list representation of the        // connected edges by declaring List class object        // Declaring object of type List<Node>        List<List<Node> > adj            = new ArrayList<List<Node> >();         // Initialize list for every node        for (int i = 0; i < V; i++) {            List<Node> item = new ArrayList<Node>();            adj.add(item);        }         // Inputs for the GFG(dpq) graph        adj.get(0).add(new Node(1, 9));        adj.get(0).add(new Node(2, 6));        adj.get(0).add(new Node(3, 5));        adj.get(0).add(new Node(4, 3));         adj.get(2).add(new Node(1, 2));        adj.get(2).add(new Node(3, 4));         // Calculating the single source shortest path        GFG dpq = new GFG(V);        dpq.dijkstra(adj, source);         // Printing the shortest path to all the nodes        // from the source node        System.out.println("The shorted path from node :");         for (int i = 0; i < dpq.dist.length; i++)            System.out.println(source + " to " + i + " is "                               + dpq.dist[i]);    }} // Class 2// Helper class implementing Comparator interface// Representing a node in the graphclass Node implements Comparator<Node> {     // Member variables of this class    public int node;    public int cost;     // Constructors of this class     // Constructor 1    public Node() {}     // Constructor 2    public Node(int node, int cost)    {         // This keyword refers to current instance itself        this.node = node;        this.cost = cost;    }     // Method 1    @Override public int compare(Node node1, Node node2)    {         if (node1.cost < node2.cost)            return -1;         if (node1.cost > node2.cost)            return 1;         return 0;    }}
  
The shorted path from node :
0 to 0 is 0
0 to 1 is 8
0 to 2 is 6
0 to 3 is 5
0 to 4 is 3
 
 
jyoti369
iramkhalid24
germanshephered48
Dijkstra
java-priority-queue
Picked
Shortest Path
Java Programs
Shortest Path
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Java Programming Examples
How to Iterate HashMap in Java?
Factory method design pattern in Java
Traverse Through a HashMap in Java
Iterate through List in Java
Java Program to Remove Duplicate Elements From the Array
Java program to count the occurrence of each character in a string using Hashmap
Iterate Over the Characters of a String in Java
Min Heap in Java
How to Get Elements By Index from HashSet in Java?