Explain Dijkstra's algorithm for finding shortest path with an example.


Q.) Explain Dijkstra's algorithm for finding shortest path with an example.

Subject: Data Structures

Dijkstra's algorithm is a popular algorithm used to find the shortest path between nodes in a graph, which may represent, for example, road networks. This algorithm was invented by Edsger W. Dijkstra in 1956.

The algorithm works by building up a set of nodes that have minimum distance from the source. It begins with a 'current node' (usually the source node), and then visits the nodes connected to the current node with the smallest weights first, then going to next closest sibling, and so on. This process continues until all the nodes in the graph have been visited.

Here is a step-by-step approach to Dijkstra's algorithm:

  1. Initialization: Set the initial node as current. Mark all other nodes as unvisited. Create a set of all the unvisited nodes called the unvisited set. Assign to every node a tentative distance value: set it to zero for our initial node and to infinity for all other nodes.

  2. Current Node: For the current node, consider all of its unvisited neighbors and calculate their tentative distances through the current node. Compare the newly calculated tentative distance to the current assigned value and assign the smaller one.

  3. Visiting Nodes: When we are done considering all of the unvisited neighbors of the current node, mark the current node as visited and remove it from the unvisited set. A visited node will never be checked again.

  4. Next Node: If the destination node has been marked visited or if the smallest tentative distance among the nodes in the unvisited set is infinity (occurs when there is no connection between the initial node and remaining unvisited nodes), then stop. The algorithm has finished. Otherwise, select the unvisited node that is marked with the smallest tentative distance, set it as the new "current node", and go back to step 2.

Let's illustrate this with an example:

Consider the following graph:

A --1-- B --2-- D
|      / \      |
4     2   3     1
|   /     |     |
C --5-- E --1-- F

We want to find the shortest path from A to F.

Step Current Node Visited Nodes Unvisited Nodes Shortest Path Found
1 A A B(1), C(4) A->B(1), A->C(4)
2 B A, B C(3), D(3), E(4) A->B->C(3), A->B->D(3), A->B->E(4)
3 C A, B, C D(3), E(4), F(8) A->B->C->F(8), A->B->D(3), A->B->E(4)
4 D A, B, C, D E(4), F(4) A->B->D->F(4), A->B->E(4)
5 F A, B, C, D, F E(4) A->B->D->F(4)
6 E A, B, C, D, F, E - A->B->D->F(4)

So, the shortest path from A to F is A->B->D->F with a total distance of 4.