GraphsMedium
Graph Traversal: Deep Dive into DFS and BFS
Explore depth-first search and breadth-first search algorithms with visual examples and implementation details.
December 20, 2024
14 min read
GraphsDFSBFSTraversal
Graph Traversal: Deep Dive into DFS and BFS
Graph traversal is fundamental to solving many algorithmic problems. Understanding DFS and BFS is crucial.
Depth-First Search (DFS)
DFS explores as far as possible along each branch before backtracking.
Recursive Implementation
def dfs_recursive(graph, node, visited):
visited.add(node)
print(node)
for neighbor in graph[node]:
if neighbor not in visited:
dfs_recursive(graph, neighbor, visited)Iterative Implementation
def dfs_iterative(graph, start):
visited = set()
stack = [start]
while stack:
node = stack.pop()
if node not in visited:
visited.add(node)
print(node)
stack.extend(reversed(graph[node]))Breadth-First Search (BFS)
BFS explores all neighbors before moving to the next level.
from collections import deque
def bfs(graph, start):
visited = set()
queue = deque([start])
visited.add(start)
while queue:
node = queue.popleft()
print(node)
for neighbor in graph[node]:
if neighbor not in visited:
visited.add(neighbor)
queue.append(neighbor)When to reach for each style
DFS is a strong default when
BFS shines when
Common applications
Both stay essential tools in your algorithmic toolkit.
Related Articles
Trees
Comprehensive coverage of tree data structures, including DFS, BFS, tree construction, and common interview problems.