AlgoFrames

Fewest edges between two nodes

Standard · Write code · about 12 min

Return the smallest number of edges on a path from source to target, or -1 if no path exists. Directed graphs follow edge direction. 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 < n
  • At most 3n edges; repeated edges and self-loops may appear
  • 0 ≤ target < n

Learn the idea first: Breadth-first search, a visual lesson.

More Breadth-first search problems