#1971
Easy Algorithms Find if path exists in graph
Depth-First Search Breadth-First Search Union-Find Graph Theory
54.8% acceptance
Feb 25, 2026
4288
252
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.
Solution
Rust
Time O(n)
Space O(n)
impl Solution {
pub fn valid_path(n: i32, edges: Vec<Vec<i32>>, source: i32, destination: i32) -> bool {
let n = n as usize;
let mut parent: Vec<usize> = (0..n).collect();
fn find(parent: &mut Vec<usize>, x: usize) -> usize {
if parent[x] != x {
parent[x] = find(parent, parent[x]);
}
parent[x]
}
for edge in &edges {
let a = find(&mut parent, edge[0] as usize);
let b = find(&mut parent, edge[1] as usize);
parent[a] = b;
}
find(&mut parent, source as usize) == find(&mut parent, destination as usize)
}
}