Find if Path Exists in Graph
Find if Path Exists in Graph is LeetCode 1971 (Easy). A graph has n vertices labelled 0 to n - 1, and each pair [u, v] in edges is an undirected edge. Return true if some path connects source to destination, and false otherwise.
- There are no duplicate edges and no edge from a vertex to itself.
- Only whether a path exists matters, not how long it is.
With up to 2 × 10⁵ vertices and edges, the search must be linear in their total.
- 1 <= n <= 2 * 10⁵
- 0 <= edges.length <= 2 * 10⁵
- edges[i].length == 2
- 0 <= ui, vi <= n - 1
- ui != vi
- 0 <= source, destination <= n - 1
- There are no duplicate edges.
- There are no self edges.
Intuition
Start at source and mark every vertex you can reach. The answer is true exactly when destination gets marked. Any search that visits each reachable vertex once will do; this one uses a stack.
- Only reachable vertices get marked: a vertex is pushed only from a neighbour that was itself reached.
- Every reachable vertex gets marked: follow any path from
source. If some vertex on it stayed unmarked, the vertex just before it was marked and popped, and popping it would have pushed its neighbour. So no vertex on the path is missed.
"Can I get from A to B?" with no weights is plain reachability: one DFS or BFS from A, or union-find over the edges. Number of Provinces, Keys and Rooms and flood-fill grid problems are this same marking walk.
Approach
Before reading on: with n = 6, edges = [[0,1],[0,2],[3,5],[5,4],[4,3]], source = 0 and destination = 5, list the vertices a search from 0 can mark. What tells the search it can stop and answer false?
Build an undirected adjacency list
Make n empty lists. For each pair [u, v], append v to adj[u] and u to adj[v], because an undirected edge can be walked from either end. The search then finds a vertex's neighbours without scanning the edge list.
Mark the source and push it
Set seen[source] = True and start the stack as [source]. Marking it now means no neighbour can push it back later. If source == destination, the very first pop finds the answer, so that case needs no special code.
Pop a vertex and compare it with the destination
Pop u from the stack. If u == destination, return true right away: a path exists, and the rest of the stack does not matter.
Push every neighbour not yet seen
For each v in adj[u] with seen[v] still false, set seen[v] = True and push v. Marking at push time means each vertex enters the stack at most once, which keeps the work at one visit per vertex and two checks per edge.
Return false when the stack is empty
An empty stack means every vertex reachable from source has been popped and none was the destination. The destination lies in another piece of the graph, so no path exists.
Code in Python, C++ and Java
[u, v] is a road that works in both directions, so v goes into u's list and u into v's list. The lists on the right are what the search reads; the edge pairs themselves are not looked at again.[u, v] is a road that works in both directions, so v goes into u's list and u into v's list. The lists on the right are what the search reads; the edge pairs themselves are not looked at again.Common pitfalls
Adding each edge in one direction only
for u, v in edges:
adj[u].append(v)for u, v in edges:
adj[u].append(v)
adj[v].append(u)With n = 2, edges = [[1, 0]], source = 0, destination = 1, vertex 0 gets no neighbours, the stack empties after one pop and the answer comes out false. The edge works both ways, so the answer is true.
Recursive DFS on a long chain
def dfs(u):
seen[u] = True
return u == destination or any(
dfs(v) for v in adj[u] if not seen[v])stack = [source]
while stack:
u = stack.pop()For edges = [[0,1], [1,2], ..., [199998,199999]] with source = 0 and destination = 199999, each call waits on the next, 2 × 10⁵ deep. Python raises RecursionError at about 1,000, and raising the limit that far can crash the interpreter. An explicit stack has no depth limit.
Using an adjacency matrix
adj = [[False] * n for _ in range(n)]
adj = [[] for _ in range(n)]
At n = 2 × 10⁵ the matrix has 4 × 10¹⁰ cells, far beyond the memory limit, and scanning a row to find neighbours costs O(n) per vertex. Lists store only the 2 × 10⁵ edges that exist.
Edge cases
source == destination, for example n = 1, edges = []The source is pushed and then popped as the first vertex, it equals the destination, and the answer is true without reading any edge.
Complexity
seen and the stack hold at most V.Find if Path Exists in Graph FAQ
Should this use DFS, BFS or union-find?
All three pass. BFS is this code with a queue in place of the stack. Union-find joins the two ends of every edge and then checks whether source and destination have the same root; it needs no adjacency list and pays off when many source and destination pairs are asked about one fixed graph. For a single question, the stack search is the simplest.
Why mark a vertex when it is pushed instead of when it is popped?
Marking on pop still gives the right answer, but a vertex can then be pushed once by every neighbour before it is popped. In a graph where one vertex links to every other and they all link to each other, the stack can grow to about E entries instead of at most V. Marking on push caps it at V.