Shortest path length
Standard · Write code · about 10 min
Return the number of edges on a shortest path from source to target, or -1 if target cannot be reached. Every edge counts as 1. Directed graphs follow edge direction. 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:
2
Path 0, 3, 4 uses 2 edges.
Example 2
Input:
[{"n":5,"edges":[[0,1],[0,2],[2,1],[1,3],[4,0]],"directed":true},0,4]
Output:
-1
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
- Which search finds the fewest stops? Warm-up
- Distance labels Warm-up
- Reconstruct the path Standard
- Nearest exit in a maze Standard
- Spot the bug: wrong distances Standard
- Word ladder Challenge