Dijkstra’s shortest path algorithm in Java using PriorityQueue
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)
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.
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
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)
Please Login to comment...