Graph Depth First Search
Note
🛑 We strongly suggest getting comfortable with graphs before you start. Otherwise this section will be very confusing :)
Overview
Graph depth first search, usually just called depth first search (DFS), is the most straightforward way to traverse a graph.
DFS works especially well for two kinds of graph problems:
- Validation Problems ask whether something is true about a graph. Usually that means checking whether a node exists in the graph or whether two nodes are connected.
- Path Problems also ask for a path. Besides checking a condition, you also return the path to a node. For example, you might return the nodes of a cycle if the graph has one.
Note
You can solve a lot of DFS problems with breadth first search too. In interviews, DFS is usually the better pick because it's simpler and works for more problems. The backtracking pattern is actually DFS used in a particular way.
Pattern concept
Let's walk through a basic graph path problem:
Use ← → arrow keys
Solution templates
- Validation problems: you check whether a condition is true.
- Path problems: you check a condition and also return the path you took.
Validation Problem
An example validation problem: Return whether node 0 is connected to node 4.
# === Recursive helper function ===
def dfs(curr: str, target: str, graph: Dict[str, List[str]], visited: Set):
# === Visited Check ===
visited.add(curr)
# === Result Check ===
if curr == target:
return True
# === Recursive Find ===
# Check if recursing into ANY unvisited neighbors will reach the target.
for node in graph[curr]:
if node not in visited:
if dfs(node, target, graph, visited):
return True
return False # No neighbors led to the target.
# === Original function ===
def find_node(edges: List[List[str]], start: str, target: str) -> bool:
# === Graph Initialization ===
# Decide if we should build an undirected vs directed graph.
graph = defaultdict(list)
for edge in edges:
graph[edge[0]].append(edge[1])
graph[edge[1]].append(edge[0])
# === DFS Initialization ===
visited = set()
return dfs(start, target, graph, visited)
print(find_node([["0", "1"], ["1", "2"], ["2", "3"], ["1", "4"]], "0", "4"))
Path Problem
An example path problem: If node 0 is connected to node 4, return the path.
# ==== Recursive helper function ====
def dfs(curr: str, target: str, graph: Dict[str, List[str]], visited: Set, res: List[int]):
# === Visited Check ===
visited.add(curr)
# === Result Check ===
if curr == target:
return True
# === Recursive Find ===
# Remember to update the result path BEFORE and AFTER
# recursing into unvisited neighbors.
for node in graph[curr]:
if node not in visited:
res.append(node)
if dfs(node, target, graph, visited, res):
return True
res.pop()
return False # No neighbors led to the target.
# ==== Original function ====
def find_node(edges: List[List[str]], start: str, target: str) -> bool:
# === Graph Initialization ===
# Decide if we should build an undirected vs directed graph.
graph = defaultdict(list)
for edge in edges:
graph[edge[0]].append(edge[1])
graph[edge[1]].append(edge[0])
# === DFS Initialization ===
visited = set()
res = [start]
if dfs(start, target, graph, visited, res) == True:
return res
return []
print(find_node([["0", "1"], ["1", "2"], ["2", "3"], ["1", "4"]], "0", "4"))
Note
The code changes slightly depending on whether you build a directed or an undirected graph. Ask yourself this question to decide: is there a dependency between nodes in the graph?
How to identify
Does the problem involve any of these?
- Finding the number of connected components in a graph
- Number of Connected Components: Count the connected components in a graph.
- Number of Islands: Count the groups of connected land in a grid.
- Exploring paths or connections between nodes in a graph
- Return whether node A is connected to node B.
- Return the path from node A to node B if they're connected.
- Pacific Atlantic Water Flow: Return which cells on the grid can have water flowing to certain borders of the grid.
- Course Schedule: Determine if a valid order exists between courses.
- Exploring combinations that satisfy a condition (covered later)
Note
Depth first search usually takes O(n + e) time, where n is the number of nodes and e is the number of edges. A traversal visits each node and edge once.