Find if Path Exists in Graph - Problem
Imagine you're planning a trip through a network of cities connected by bidirectional roads. You have a map showing all the connections, and you need to determine if it's possible to travel from your starting city to your destination.
Given a bidirectional graph with n vertices labeled from 0 to n-1, where edges are represented as a 2D array edges[i] = [ui, vi], determine if there's a valid path from source to destination.
Key points:
- The graph is undirected - you can travel both ways on any road
- No city connects to itself
- At most one direct road exists between any two cities
- Return
trueif a path exists,falseotherwise
Input & Output
example_1.py β Simple Path
$
Input:
n = 3, edges = [[0,1],[1,2],[2,0]], source = 0, destination = 2
βΊ
Output:
true
π‘ Note:
There are two paths from vertex 0 to vertex 2: 0 β 1 β 2 and 0 β 2. Both paths are valid.
example_2.py β Disconnected Graph
$
Input:
n = 6, edges = [[0,1],[0,2],[3,5],[5,4],[4,3]], source = 0, destination = 5
βΊ
Output:
false
π‘ Note:
There is no path from vertex 0 to vertex 5. Vertices 0,1,2 form one connected component while vertices 3,4,5 form another separate component.
example_3.py β Same Source and Destination
$
Input:
n = 1, edges = [], source = 0, destination = 0
βΊ
Output:
true
π‘ Note:
Since source equals destination, we are already at the target. No movement needed.
Visualization
Tap to expand
Understanding the Visualization
1
Build the Road Network
Convert the edges array into an adjacency list representing bidirectional roads between cities
2
Start the Journey
Begin exploration from the source city, marking it as visited to avoid going in circles
3
Explore Connected Cities
Visit each neighboring city that hasn't been visited yet, continuing the search recursively
4
Destination Found!
If we reach the destination city, return true. If all reachable cities are explored without finding destination, return false
Key Takeaway
π― Key Insight: Graph connectivity problems are efficiently solved using DFS/BFS traversal with visited tracking or Union-Find for multiple queries. The key is recognizing that we only need to check if two nodes belong to the same connected component.
Time & Space Complexity
Time Complexity
O(V + E)
Visit each vertex once and traverse each edge once in worst case
β Linear Growth
Space Complexity
O(V + E)
Adjacency list storage O(V + E) plus visited set O(V) plus recursion stack O(V)
β Linear Space
Constraints
- 1 β€ n β€ 2 Γ 105
- 0 β€ edges.length β€ 2 Γ 105
- edges[i].length == 2
- 0 β€ ui, vi β€ n - 1
- ui != vi
- 0 β€ source, destination β€ n - 1
- There are no duplicate edges and no self edges
π‘
Explanation
AI Ready
π‘ Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code