The Dijkstra Protocol

HardAcc. 58.4%
+100 XP 50

The Shortest Path Cartographer

Dijkstra's Algorithm is the "GPS" of the computing world. It finds the shortest distance from one point to every other point in a weighted network by always choosing the "cheapest" path currently known.

The Assignment

Your mission is to map out the most efficient routes. Your function receives a graph and a startNode.

  1. Create a distances map, initializing all points to Infinity, except the startNode (which is 0).
  2. Use a loop (or a Priority Queue) to find the unvisited node with the smallest known distance.
  3. For that node, check all its neighbors:
    • Calculate the distance to the neighbor through the current node.
    • If this new path is shorter than the previously known distance, update the map.
  4. Print the final distance map (Sorted by node ID string).

01EXAMPLE 1

Inputn=3, adj=[[0, 1, 5], [1, 0, 2], [5, 2, 0]]
Output0 1 3

Explanation: Path 0->1->2 is 3, while 0->2 is 5.

Constraints

  • O(V^2) implementation is acceptable (no priority queue required).
GraphsAlgorithms
JavaScript
Loading...
1 Hidden

Input Arguments

n3
adj[[0,1,5],[1,0,2],[5,2,0]]

Expected Output

0
1
3

Click RUN to test your solution