AlgoFrames

Implement Dijkstra

Standard · Write code · about 15 min

Return an array dist where dist[v] is the length of the shortest path from source to v, or -1 when v is unreachable. Weights are non-negative. buildAdjacency(graph) lists [neighbor, weight] pairs.

In Python, build the adjacency lists from graph["edges"] yourself.

Example 1

Input:

[{"n":5,"edges":[[0,1,4],[0,2,1],[2,1,2],[1,3,5],[3,4,3]],"directed":false},0]

Output:

[0,3,1,8,11]

Node 1 is 3 away through node 2.

Example 2

Input:

[{"n":6,"edges":[[0,1,7],[0,2,2],[2,1,3],[1,3,1],[2,3,6],[3,4,2]],"directed":true},0]

Output:

[0,5,2,6,8,-1]

Edges are one-way.

Constraints

  • 1 ≤ n ≤ 100
  • 0 ≤ source < n
  • 0 ≤ weight ≤ 100

Learn the idea first: Dijkstra's algorithm, a visual lesson.

More Dijkstra's algorithm problems