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.
- Create a
distancesmap, initializing all points to Infinity, except thestartNode(which is 0). - Use a loop (or a Priority Queue) to find the unvisited node with the smallest known distance.
- 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.
- Print the final distance map (Sorted by node ID string).
01EXAMPLE 1
Input
n=3, adj=[[0, 1, 5], [1, 0, 2], [5, 2, 0]]Output
0
1
3Explanation: Path 0->1->2 is 3, while 0->2 is 5.
Constraints
- O(V^2) implementation is acceptable (no priority queue required).
GraphsAlgorithms
JavaScriptSystem handles I/O — write your function only
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