sagelearnai

Find if Path Exists in Graph

Difficulty: Easy · Pattern: Graphs (BFS / DFS) · LeetCode #1971

An undirected graph has n vertices 0 … n−1 and an edge list edges. Return true if there's a path between source and destination.

Examples

text
n = 3, edges = [[0,1], [1,2], [2,0]], source = 0, destination = 2   →  true
n = 6, edges = [[0,1], [0,2], [3,5], [5,4], [4,3]], source = 0, destination = 5   →  false

Hints

  1. BFS/DFS from the source works.
  2. Or union every edge's endpoints, then check whether source and destination share a root.

Approach

Create a DSU over n nodes and union the endpoints of every edge. A path exists iff find(source) == find(destination). With path compression and union by size, this is O((n + E)·α(n)).

Complexity

Time: O((n + E)·α(n)). Space: O(n).

Python solution
def validPath(n, edges, source, destination):
    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)
JavaScript solution
function validPath(n, edges, source, destination) {
  const parent = Array.from({ length: n }, (_, i) => i);
  const find = (x) => { while (parent[x] !== x) { parent[x] = parent[parent[x]]; x = parent[x]; } return x; };
  for (const [a, b] of edges) parent[find(a)] = find(b);
  return find(source) === find(destination);
}