AlgoFrames

Is there a path?

Standard · Write code · about 10 min

Return true when target can be reached from source by following edges, and false otherwise. A node reaches itself. For directed graphs follow edges only in their direction.

Example 1

Input:

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

Output:

true

Path 0, 1, 3, 4.

Example 2

Input:

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

Output:

false

Nodes 0-1 and 2-3 are separate parts.

Constraints

  • 1 ≤ n ≤ 100
  • 0 ≤ source, target < n

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

More Depth-first search problems