Sub topic 15
Choosing Between BFS and DFS
This chapter assumes you know the BFS loop from earlier chapters, Python lists and sets, and Big-O notation. Depth-first search (DFS) is the other basic way to traverse a graph. It follows one path as far as it can go, then backs up and tries the next branch. Both algorithms run in O(V + E) time on an adjacency list. They differ in the order they visit vertices, in how much memory they need, and in which questions that order can answer.
Same graph, different order
The only structural difference is the container. BFS takes the oldest vertex from a FIFO queue. DFS takes the newest vertex from a LIFO stack.
from collections import deque
def bfs(graph, start):
visited = {start}
order = []
queue = deque([start])
while queue:
node = queue.popleft()
order.append(node)
for neighbor in graph[node]:
if neighbor not in visited:
visited.add(neighbor)
queue.append(neighbor)
return order
def dfs(graph, start):
visited = set()
order = []
stack = [start]
while stack:
node = stack.pop()
if node in visited:
continue
visited.add(node)
order.append(node)
for neighbor in reversed(graph[node]):
if neighbor not in visited:
stack.append(neighbor)
return order
graph = {
'A': ['B', 'C'],
'B': ['D'],
'C': ['D', 'E'],
'D': ['F'],
'E': ['F'],
'F': [],
}
print(bfs(graph, 'A')) # ['A', 'B', 'C', 'D', 'E', 'F']
print(dfs(graph, 'A')) # ['A', 'B', 'D', 'F', 'C', 'E']BFS finishes every vertex one edge away before it moves to vertices two edges away. DFS reaches F through B and D before it ever looks at C. The iterative DFS marks a vertex visited when it is popped, not when it is pushed. Marking on push would still visit every reachable vertex, but the order would no longer match recursive DFS.
Comparing the two
| Question | BFS | DFS |
|---|---|---|
| Fewest-edge path from a source | Yes, by construction | No, the first path found can be long |
| Memory on a wide, shallow graph | High, the queue holds a whole layer | Low |
| Memory on a deep, narrow graph | Low | High, the stack holds the whole path |
| Cycle detection in directed graphs | Awkward | Natural, using a "currently on the path" marker |
| Topological order | Possible with Kahn's algorithm | Natural, using finish order |
| Bipartiteness, layers, distances | Natural | Possible, but less direct |
| Exhaustive search and backtracking | Rarely used | Natural |
Decision criteria
If the answer depends on distance, use BFS. If the answer depends on the structure of paths, such as whether one loops back on itself or which vertices must come before others, use DFS. If you only need reachability or connected components, either one works, so pick the one with the better memory profile for your graph's shape.
Common mistakes
- Using DFS for shortest paths in an unweighted graph, then "fixing" it by keeping a running minimum. That can explore exponentially many paths.
- Replacing
popleft()withpop()by accident. The code still runs, but it has become a form of DFS, and the distances it reports are wrong. - Choosing BFS on a graph with branching factor b and solution depth d, then running out of memory. The frontier alone can hold about b^d vertices.
Exercise
You must decide whether a directed dependency graph contains a cycle, and you must also find the minimum number of moves for a knight to cross a chessboard. Which traversal fits each task, and why?
Show answer
Use DFS for the cycle check. A directed graph has a cycle exactly when DFS finds an edge to a vertex that is still on the current path, and BFS does not track that path. Use BFS for the knight problem. Every move costs one edge, so BFS layers give the minimum number of moves.
Exercise
In the code above, what does dfs(graph, 'C') return?
Show answer
['C', 'D', 'F', 'E']. From C, the search goes to D and then F. It then backtracks and visits E, whose neighbor F has already been visited.