1971. Find if Path Exists in Graph
Problem
Decide whether there is a path from source to destination in an undirected graph with nodes 0…n − 1 and the given edges.
Example: n = 3, edges = [[0,1],[1,2],[2,0]], source = 0, destination = 2 → true
Constraints: up to 2·10⁵ nodes and edges.
Union every edge, then check whether source and destination share a root (or BFS from the source).
Complexity: O(E · α(V)).
class Solution:
def validPath(self, n: int, edges: List[List[int]], source: int, destination: int) -> bool:
parent = list(range(n))
def find(x):
while parent[x] != x:
parent[x] = parent[parent[x]]
x = parent[x]
return x
for a, b in edges:
parent[find(a)] = find(b)
return find(source) == find(destination)
assert Solution().validPath(3, [[0, 1], [1, 2], [2, 0]], 0, 2) is True
assert Solution().validPath(6, [[0, 1], [0, 2], [3, 5], [5, 4], [4, 3]], 0, 5) is False
class Solution {
public boolean validPath(int n, int[][] edges, int source, int destination) {
int[] p = new int[n];
for (int i = 0; i < n; i++) p[i] = i;
for (int[] e : edges) p[find(p, e[0])] = find(p, e[1]);
return find(p, source) == find(p, destination);
}
private int find(int[] p, int x) {
while (p[x] != x) { p[x] = p[p[x]]; x = p[x]; }
return x;
}
}
func validPath(n int, edges [][]int, source int, destination int) bool {
parent := make([]int, n)
for i := range parent {
parent[i] = i
}
find := func(x int) int {
for parent[x] != x {
parent[x] = parent[parent[x]]
x = parent[x]
}
return x
}
for _, e := range edges {
parent[find(e[0])] = find(e[1])
}
return find(source) == find(destination)
}