Dijkstra's Algorithm

Introduction: Dijkstra's algorithm allows us to find the shortest path between any two vertices of a graph. It differs from the minimum spanning tree because the shortest distance between two vertices might not include all the vertices of the graph.



WORKING OF Dijkstra's:

Djikstra used this property in the opposite direction i.e we overestimate the distance of each vertex from the starting vertex. Then we visit each node and its neighbors to find the shortest subpath to those neighbors.
The algorithm uses a greedy approach in the sense that we find the next best solution hoping that the end result is the best solution for the whole problem.

Example

Step 1: Start with a weighted graph

Step 2: Choose a starting vertex and assign infinity path values to all other devices

Step 3: Go to each vertex and update its path length

Step 4: If the path length of the adjacent vertex is lesser than new path length, don't update it

Step 5: Avoid updating path lengths of already visited vertices

Step 6: After each iteration, we pick the unvisited vertex with the least path length. So we choose 5 before 7

Step 7: Notice how the rightmost vertex has its path length updated twice

Step 8: Repeat until all the vertices have been visited


Dijkstra's Algorithm Complexity

Time Complexity: O(E Log V)
where, E is the number of edges and V is the number of vertices.
Space Complexity: O(V)