Dijkstra algorithm gets its name from the Dutch computer scientist Edsger Dijkstra who invented this algorithm in 1959. It is used to find the shortest path between two non-negative nodes in a graph. Dijkstra algorithm is widely used for the purpose of routing.

For any giving node in a graph the algorithm finds the path which is the shortest from that node to all the corresponding nodes in the graph. As stated earlier also that this algorithm is used to find the shortest path between two distinct nodes on the graph, e.g., suppose there are two cities X and Y and there are three different path of going to cities Y from X, then Dijkstra algorithm finds out the shortest path between these two cities X and Y.

In the above example, the shortest path could be found on the basis of distance in Kilometers or on the basis of time taken on each path. The following figure will illustrate the example in more detail.

As the above figure shows there are three ways of going from city X to city Y. First is to take the Highway which is 25km long, second, is to take the tunnel which is 15km long and last is through city Z which is 20 km long. Now through Dijkstra algorithm we can find out that the shortest path between city X and Y is through the tunnel which is just 15km long.

But what if time was the key factor in finding out the shortest path between the two cities? Now consider the time taken on the highway, tunnel and through city Z are 1hour, 1 hour 30 min and 2 hour respectively, then the shortest path will be the highway since it take the shortest time to reach city Y.

C++ implementation

Output: