Find if Path Exists in Graph
LeetCode 1971 · Easy · solution, intuition & step-by-step walkthrough
BFS reachability.
This is how I solved Find if Path Exists in Graph (LeetCode 1971), an easy problem from the Graph Fundamentals / DFS-BFS pattern. Below: the intuition, the approach step by step, my accepted Python code, animated test cases and a line-by-line debugger.
Intuition
Build the undirected graph and BFS from the source; the destination is reachable exactly when BFS visits it.
Approach
- 1
Adjacency list both ways.
- 2
BFS from source; return True when destination is popped.
How I solved it
BFSPythonO(V+E) time
class Solution:
def validPath(self, n: int, edges: List[List[int]], source: int, destination: int) -> bool:
adj = defaultdict(list)
for u,v in edges:
adj[u].append(v)
adj[v].append(u)
q = deque([source])
visited = set()
while q:
node = q.popleft()
if node==destination:
return True
for adj_node in adj[node]:
if adj_node not in visited:
visited.add(adj_node)
q.append(adj_node)
return FalseFind if Path Exists in Graph — FAQ
What is the intuition behind Find if Path Exists in Graph?
Build the undirected graph and BFS from the source; the destination is reachable exactly when BFS visits it.
How do you solve Find if Path Exists in Graph (LeetCode 1971)?
1. Adjacency list both ways. 2. BFS from source; return True when destination is popped.
What is the time and space complexity of Find if Path Exists in Graph?
Time: O(V + E). Space: O(V + E). (Accepted approach: BFS.)
What are common mistakes in Find if Path Exists in Graph?
source == destination is trivially True.