Start learning free

LESSON 565 OF 679 · GRAPHS

Depth First Search (DFS): Find if Path Exists in Graph

Practice O(V+E)

You get an undirected graph with n vertices, labeled 0 to n - 1. Each entry edges[i] = [ui, vi] joins vertices ui and vi. You can follow an edge in both directions.

Return true if you can walk along edges from vertex source to vertex destination. Otherwise, return false. A vertex always reaches itself.

 

Example 1:

3 0 4 2 1
Input: n = 5, edges = [[3,0],[0,4],[4,2],[2,1],[1,4]], source = 3, destination = 1
Output: true
Explanation: The blue edges show the path 3 → 0 → 4 → 1.
The path 3 → 0 → 4 → 2 → 1 also works.

Example 2:

0 5 2 1 3 4
Input: n = 6, edges = [[0,5],[5,2],[1,3],[3,4]], source = 2, destination = 4
Output: false
Explanation: The graph has two separate parts.
From 2, you can only reach 5 and 0.
No edge leads to the part with 1, 3 and 4.

Example 3:

0 1 2
Input: n = 3, edges = [[1,2]], source = 0, destination = 0
Output: true
Explanation: Vertex 0 has no edges.
But source and destination are the same vertex.
The walk starts and ends right there.

 

Constraints:

  • 2 to 200,000 vertices.
  • At most 200,000 entries in edges.
  • Every vertex in edges is from 0 to n - 1. So are source and destination.
  • No edge joins a vertex to itself.
  • The same edge can be listed twice, for example as [1, 4] and [4, 1].
STEP 1 OF 10
    Ctrl + Enter to check