Depth-First Search (DFS)
Depth-First Search (DFS)
DFS explores a graph by going as deep as possible along each branch before backtracking. It follows one path until it reaches a dead end, then backs up to the last unexplored branch. This creates a winding, depth-first exploration pattern.
How It Works
- Start at the source node, push it onto the stack
- Pop the top node from the stack
- If not visited, mark it visited and process it
- Push all its unvisited neighbors onto the stack
- Repeat until the stack is empty or the goal is found
The stack (LIFO) is what creates the depth-first property — the most recently discovered node is explored first.
Code Snippet
Uses the Graph class from the Graphs and Weighted Graphs article:
def depth_first_search(graph, start_node: int, goal_node: int) -> list[int]:
"""Find a path from start to goal (not necessarily shortest)."""
visited = [False] * graph.num_nodes
parent_of = [-1] * graph.num_nodes
stack = [start_node]
found = False
while stack:
current_node = stack.pop()
if visited[current_node]:
continue
visited[current_node] = True
if current_node == goal_node:
found = True
break
for neighbor in graph.get_neighbors(current_node):
if not visited[neighbor]:
parent_of[neighbor] = current_node
stack.append(neighbor)
if not found:
return []
# Reconstruct path
path = []
node = goal_node
while node != -1:
path.append(node)
node = parent_of[node]
path.reverse()
return path
Recursive Version
DFS maps naturally to recursion (the call stack acts as the explicit stack):
def dfs_recursive(graph, current_node: int, goal_node: int,
visited: list[bool], path: list[int]) -> bool:
"""Recursive DFS. Returns True if goal is reachable."""
visited[current_node] = True
path.append(current_node)
if current_node == goal_node:
return True
for neighbor in graph.get_neighbors(current_node):
if not visited[neighbor]:
if dfs_recursive(graph, neighbor, goal_node, visited, path):
return True
path.pop() # backtrack
return False
DFS Does Not Guarantee Shortest Path
DFS explores depth-first, so it might find a long winding path when a short direct path exists. It finds a path, not the shortest path.
Time and Space Complexity
- Time: O(V + E) — same as BFS, visits each node and edge once
- Space: O(V) — the stack stores at most the depth of the graph (O(V) worst case for a long chain)
In practice, DFS uses less memory than BFS on wide graphs because it only stores the current path depth, not the entire frontier width.
When to Use DFS
- Detecting cycles in a graph
- Topological sorting (processing dependencies)
- Solving puzzles with backtracking (Sudoku, N-Queens, maze generation)
- Finding connected components
- When you need any path, not the shortest
- When the graph is deep but narrow (memory advantage over BFS)