AlgoFrames

Reconstruct the path

Standard · Write code · about 12 min

Return one shortest path from source to target as a list of nodes, starting with source and ending with target. Return [] if target cannot be reached. When several shortest paths exist, any one is accepted. In JavaScript, buildAdjacency(graph) returns the adjacency lists.

Example 1

Input:

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

Output:

[0,3,4]

Path 0, 3, 4 is the only shortest path.

Example 2

Input:

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

Output:

[]

The only edge at 4 points into 0.

Constraints

  • 1 ≤ n ≤ 200 nodes, numbered 0 to n - 1
  • 0 ≤ source, target < n
  • At most 3n edges; repeated edges and self-loops may appear
  • Directed graphs follow edge direction

Learn the idea first: Shortest paths in unweighted graphs; path reconstruction, a visual lesson.

More Shortest paths in unweighted graphs; path reconstruction problems