Find if Path Exists in Graph - Problem
There is a bi-directional graph with n vertices, where each vertex is labeled from 0 to n - 1 (inclusive). The edges in the graph are represented as a 2D integer array edges, where each edges[i] = [ui, vi] denotes a bi-directional edge between vertex ui and vertex vi. Every vertex pair is connected by at most one edge, and no vertex has an edge to itself.
You want to determine if there is a valid path that exists from vertex source to vertex destination.
Given edges and the integers n, source, and destination, return true if there is a valid path from source to destination, or false otherwise.
Input & Output
Example 1 — Basic Connected Graph
$
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 are valid paths.
Example 2 — Disconnected Components
$
Input:
n = 6, edges = [[0,1],[0,2],[3,5],[5,4],[4,3]], source = 0, destination = 5
›
Output:
false
💡 Note:
Vertex 0 is in component {0,1,2} while vertex 5 is in component {3,4,5}. No path exists between them.
Example 3 — Same Source and Destination
$
Input:
n = 1, edges = [], source = 0, destination = 0
›
Output:
true
💡 Note:
Source and destination are the same vertex. A path always exists from a vertex to itself.
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
Visualization
Tap to expand
Understanding the Visualization
1
Input Graph
Given edges [[0,1],[1,2],[2,0]], we want path from 0 to 2
2
Build Adjacency List
Create bidirectional connections between vertices
3
Search Algorithm
Use DFS/BFS to explore reachable nodes from source
4
Result
Return true if destination is reachable, false otherwise
Key Takeaway
🎯 Key Insight: Graph connectivity can be solved efficiently using DFS or BFS traversal in O(V + E) time
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code