Asked at

Find If Path Exists in Graph

Easy
Verified
DFSBFSGraphUnion Find~15 min

You’re given an undirected graph with n nodes 0..n-1 and edge list edges, where edges[i] = [u, v]. Determine whether a path connects source to destination.

Return a boolean. The input arrives as a single object { n, edges, source, destination }.

Examples

in{ n: 3, edges: [[0,1],[1,2],[2,0]], source: 0, destination: 2 }
outtrue

0→2 is a direct edge.

in{ n: 6, edges: [[0,1],[0,2],[3,5],[5,4],[4,3]], source: 0, destination: 5 }
outfalse

Nodes 0 and 5 sit in different components.

Constraints

  • 1 ≤ n ≤ 2·10⁵
  • Edges are undirected: edges[i] = [u, v]
  • 0 ≤ source, destination < n

Get help

🔑

Sign in to solve

Sign in to write, run, and submit your solution — and to pick up where your iOS flow left off.