Find if Path Exists in Graph

There is a bi-directional graph with n vertices labeled 0 to n - 1. The edges are given as a 2D array edges, where edges[i] = [u, v] joins u and v. Every pair of vertices is joined by at most one edge and no vertex has an edge to itself. Return true if there is a valid path from source to destination, otherwise false.

30:00

Find if Path Exists in Graph
easy
Free written solution
Topics
Companies

There is a bi-directional graph with n vertices labeled 0 to n - 1. The edges are given as a 2D array edges, where edges[i] = [u, v] joins u and v. Every pair of vertices is joined by at most one edge and no vertex has an edge to itself. Return true if there is a valid path from source to destination, otherwise false.

Example 1:
Input: {"n":3,"edges":[[0,1],[1,2],[2,0]],"source":0,"destination":2}
Output: true
Constraints:
  • 1≤n≤2×1051 \leq n \leq 2 \times 10^5

  • 0≤edges.length≤2×1050 \leq \text{edges.length} \leq 2 \times 10^5

  • edges[i].length==2\text{edges}[i].\text{length} == 2

  • 0≤ui,vi≤n−10 \leq u_i, v_i \leq n - 1

  • ui≠viu_i \neq v_i

  • 0≤source,destination≤n−10 \leq \text{source}, \text{destination} \leq n - 1

  • There are no duplicate edges and no self edges.

Test Cases
Input (Stdin)
Expected Output (Stdout)
Execution Result

Run code to see results.

Input
arr ={"n":3,"edges":[[0,1],[1,2],[2,0]],"source":0,"destination":2}

Build an adjacency list from 3 edges. Each edge is two-way, so it is stored under both ends.

Columns = steps away from source 0

target 2

d=0d=10S12D

in queue

visited

popped now

destination / path

queue (0)

empty

visited 0

Variables
VariableValue
source0
destination2
DepthFunction Call
Stack empty
0/6