Back to All Blogs1 min read13 Sept 2026
DSA Patterns That Actually Matter · Part 5 of 5
BFS vs DFS: Choosing the Right Graph Traversal
“Understand queues, recursion, shortest paths and connected components.”
BFS vs DFS
Breadth-first search and depth-first search can both visit every reachable node.
Breadth-First Search
BFS explores level by level using a queue.
const queue = [start];
const seen = new Set([start]);
while (queue.length) {
const node = queue.shift()!;
for (const next of graph[node]) {
if (seen.has(next)) continue;
seen.add(next);
queue.push(next);
}
}
Depth-First Search
function dfs(node: number) {
seen.add(node);
for (const next of graph[node]) {
if (!seen.has(next)) {
dfs(next);
}
}
}
With an adjacency list, both typically run in O(V + E).
Use BFS when levels or shortest unweighted distance matter. Use DFS when deep recursive exploration fits naturally.
Finished this article?
Mark it done to update your series progress.