Solution Review: Shortest Distance of Each Node from the Source

This review provides a detailed analysis of the solutions to find the shortest distance of each node from the source.

Solution #1: Dijkstra’s Algorithm Using Priority Queue

Dijkstra’s algorithm is an algorithm for finding the shortest paths between nodes in a graph, which may represent, for example, road networks.

The algorithm exists in many variants. Dijkstra’s original variant found the shortest path between two nodes, but a more common variant fixes a single node as the “source” node and finds the shortest paths from the source to all other nodes in the graph, producing a shortest-path tree.

Dijkstra

Dijkstra’s algorithm finds the shortest path between a and b. It picks the unvisited vertex with the lowest distance, calculates the distance through it to each unvisited neighbor, and updates the neighbor’s distance if smaller. Mark visited (set to red) when done with neighbors.

We use STL Priority Queue for our solution. If you want to get an idea of how they are used, have a look at the appendix.

Level up your interview prep. Join Educative to access 80+ hands-on prep courses.