Dijkstra's shortest path algorithm in Java using PriorityQueue Last Updated : 13 Oct, 2022 Comments Improve Suggest changes Like Article Like Report 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 classes import java.util.*; // Main class DPQ public 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 execution 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 graph class 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; } } Output: 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 Time Complexity: O( V + E logV ) . Space Complexity: O(V+ E) Comment More infoAdvertise with us Next Article Minimum Cost using Dijkstra by Modifying Cost of an Edge A Akashkumar17 Follow Improve Article Tags : Java Dijkstra Shortest Path java-priority-queue Practice Tags : JavaShortest Path Similar Reads What is Dijkstraâs Algorithm? | Introduction to Dijkstra's Shortest Path Algorithm In this article, we will be discussing one of the most commonly known shortest-path algorithms i.e. Dijkstra's Shortest Path Algorithm which was developed by Dutch computer scientist Edsger W. Dijkstra in 1956. Moreover, we will do a complexity analysis for this algorithm and also see how it differs 10 min read Dijkstra's Algorithm to find Shortest Paths from a Source to all Given a weighted undirected graph represented as an edge list and a source vertex src, find the shortest path distances from the source vertex to all other vertices in the graph. The graph contains V vertices, numbered from 0 to V - 1.Note: The given graph does not contain any negative edge. Example 12 min read Dijkstraâs Algorithm for Adjacency List Representation | Greedy Algo-8 The Dijkstra's Algorithm, we can either use the matrix representation or the adjacency list representation to represent the graph, while the time complexity of Dijkstra's Algorithm using matrix representation is O(V^2). The time complexity of Dijkstra's Algorithm using adjacency list representation 15+ min read Printing Paths in Dijkstra's Shortest Path Algorithm Given a graph and a source vertex in the graph, find the shortest paths from the source to all vertices in the given graph.We have discussed Dijkstra's Shortest Path algorithm in the below posts. Dijkstraâs shortest path for adjacency matrix representationDijkstraâs shortest path for adjacency list 15 min read Why does Dijkstra's Algorithm fail on negative weights? Dijkstra's Algorithm: It is a graph searching algorithm that uses a Greedy Approach to find the shortest path from the source node to all other remaining nodes. It solves the single-source shortest path problem for a weighted graph. This algorithm keeps track of the weights of the edges for finding 4 min read Applications of Dijkstra's shortest path algorithm Dijkstraâs algorithm is one of the most popular algorithms for solving many single-source shortest path problems having non-negative edge weight in the graphs i.e., it is to find the shortest distance between two vertices on a graph. It was conceived by computer scientist Edsger W. Dijkstra in 1956 4 min read Dijkstra's Algorithm in different languageC / C++ Program for Dijkstra's shortest path algorithm | Greedy Algo-7Problem Statement: Given a graph and a source vertex in the graph, find the shortest paths from the source to all vertices in the given graph. What is Dijkstra's Algorithm? Dijkstra's algorithm is very similar to Prim's algorithm for minimum spanning tree. Like Prim's MST, we generate an SPT (shorte 5 min read Java Program for Dijkstra's shortest path algorithm | Greedy Algo-7Given a graph and a source vertex in the graph, find shortest paths from source to all vertices in the given graph. 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 given source as root. We maintain two s 5 min read Dijkstra's shortest path algorithm in PythonGiven a graph and a source vertex in the graph, find the shortest paths from source to all vertices in the given graph. Dijkstraâs algorithm is a popular algorithm for solving many single-source shortest path problems having non-negative edge weight in the graphs i.e., it is to find the shortest dis 4 min read C# Program for Dijkstra's shortest path algorithm | Greedy Algo-7Given a graph and a source vertex in the graph, find shortest paths from source to all vertices in the given graph. 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 given source as root. We maintain two s 5 min read Different ways to implement Dijkstra's algorithmDijkstraâs shortest path algorithm using setGiven a weighted undirected graph represented as an edge list and a source vertex src, find the shortest path distances from the source vertex to all other vertices in the graph. The graph contains V vertices, numbered from 0 to V - 1.Example:Input: src = 0, V = 5, edges[][] = [[0, 1, 4], [0, 2, 8], 8 min read Dijkstra's Shortest Path Algorithm using priority_queue of STLGiven a graph and a source vertex in graph, find shortest paths from source to all vertices in the given graph.Input : Source = 0Output : Vertex Distance from Source 0 0 1 4 2 12 3 19 4 21 5 11 6 9 7 8 8 14We have discussed Dijkstraâs shortest Path implementations.Dijkstraâs Algorithm for Adjacency 15+ min read Dijkstra's shortest path algorithm in Java using PriorityQueueDijkstraâ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 5 min read Variations of Dijkstra's algorithmMinimum Cost using Dijkstra by Modifying Cost of an EdgeGiven an undirected weighted graph of N nodes and M edges in the form of a tuple lets say {X, Y, Z} such that there is an edge with cost Z between X and Y. We are supposed to compute the minimum cost of traversal from node 1 to N. However, we can perform one operation before the traversal such that 15 min read Minimum cost path from source node to destination node via an intermediate nodeGiven an undirected weighted graph. The task is to find the minimum cost of the path from source node to the destination node via an intermediate node. Note: If an edge is traveled twice, only once weight is calculated as cost. Examples: Input: source = 0, destination = 2, intermediate = 3; Output: 12 min read Find Maximum Shortest Distance in Each Component of a GraphGiven an adjacency matrix graph[][] of a weighted graph consisting of N nodes and positive weights, the task for each connected component of the graph is to find the maximum among all possible shortest distances between every pair of nodes. Examples: Input: Output: 8 0 11 Explanation: There are thre 15+ min read Comparison of Dijkstraâs and FloydâWarshall algorithmsDijkstra AlgorithmDijkstraâs Algorithm is a Single-Source Shortest Path SSSP algorithm, i.e., given a source vertex it finds the shortest path from the source to all other vertices. The idea is to generate a SPT (shortest path tree) with a given source as a root and with two sets, one set contains v 4 min read Minimum Weight Cycle in a Graph Given an undirected, weighted graph with V vertices numbered from 0 to V-1, and E edges represented as a 2D array edges[][], where each element edges[i] = [u, v, w] denotes an edge between nodes u and v with weight w, and all edge weights are positive integers, your task is to find the minimum weigh 15+ min read Like