Consider having some cities, and a salesman wants to travel from one town (source) to another city (destination) with minimum travel distance.

Here in the below example, we have six cities with travel distances between some of them.

Below is the Dijkstra’s shortest path algorithm, which is a greedy method.

Initialize distance from the source to every other node as infinite and source to itself as 0.

Get a minimum distance node in all unvisited nodes from the source.

Calculate the total distance of all its corresponding edge nodes and update the array if the distance sum of source node to the minimum node and minimum node to all its edge nodes is minimum then update the distance.

For example., the current distance between 1 and 4 is Infinite. When we calculate it through 2, then the gap will become 5+15, which is 20. So, we update the distance infinite with the new minimum distance 20.

We keep doing the above two steps until there is no unvisited node.

Finally, the result shortest distances from the source node to all other nodes are stored.

The complexity of this algorithm is , where V is the number of vertices, and E is the number of edges in the graph.

Please see the below gist for complete code with main function.

Shortest distance from v1 to other nodes:
0
5
11
20
23
13

It is all about Dijkstra’s shortest path greedy algorithm. If you know any improvements in this code, please let our readers know by commenting here below. Happy Learning!.