iq.lab
Python starts when a code cell comes near or you run one
easyDepth-first search target 15 min

Is there a path

A graph is a set of nodes joined by edges. This graph has n nodes, numbered 0 to n - 1. Each item [a, b] in the list edges is a two-way edge: you can step from a to b and from b to a.

Return True if you can get from node source to node destination by stepping along edges, and False if you cannot. Every node can reach itself, so when source equals destination the answer is True.

No edge is listed twice, and no edge joins a node to itself.

Example 1
Inputn = 6, edges = [[0, 1], [0, 2], [1, 3], [2, 3], [4, 5]], source = 0, destination = 3OutputTrue

Step from 0 to 1, then from 1 to 3.

Example 2
Inputn = 6, edges = [[0, 1], [0, 2], [1, 3], [2, 3], [4, 5]], source = 1, destination = 5OutputFalse

Nodes 4 and 5 are joined only to each other. No edge links them to nodes 0 to 3.

Example 3
Inputn = 1, edges = [], source = 0, destination = 0OutputTrue

No step is needed to stay at node 0.

Constraints
  • 1 ≤ n ≤ 2 × 105

  • 0 ≤ len(edges) ≤ 2 × 105

  • Each edge is [a, b] with 0 ≤ a, b ≤ n - 1 and a != b. No edge is listed twice.

  • 0 ≤ source, destination ≤ n - 1

Plan it first

Write a line for each before you code, then say them out loud. Compare with the Approach tab afterwards.

⌘+Enter runs 0:00Python starts when a code cell comes near or you run one
Run examples checks the examples. Submit runs every test, including edge cases and, when the problem has one, a speed check on a large input.