Skip to main content
CSAlgorithms & ComplexityInteractiveBeginner

BFS vs DFS

KO: BFS vs DFS·EN: BFS vs DFS·JA: BFS vs DFS·Breadth-First Search vs Depth-First Search

Comparing Breadth-First Search (queue-based, level-by-level traversal) against Depth-First Search (stack/recursion, deep branch exploration)

Table of Contents

Interactive Playground

Tap or drag to interact with the demo
Quick Answer

What is BFS vs DFS?

Comparing Breadth-First Search (queue-based, level-by-level traversal) against Depth-First Search (stack/recursion, deep branch exploration). It is a core concept in Algorithms & Complexity within CS.

Core Principles

Breadth-First Search (BFS) and Depth-First Search (DFS) are the two foundational algorithms for traversing graphs and trees. Both visit every vertex and edge in O(V + E) time using an adjacency list, yet swapping a Queue for a Stack completely changes their traversal order and problem fit.

  • BFS: Uses a Queue (FIFO) to expand outward layer by layer from the source. In any unweighted graph, the first time BFS reaches a target node is mathematically guaranteed to be a shortest path.
  • DFS: Uses a Stack (LIFO) or recursion to dive as deep as possible along one branch before backtracking. It stores only the active path in memory, making it ideal for exhaustive path enumeration, cycle detection, and backtracking.

Practical Takeaways

  • Pick BFS for shortest hops and proximity: Minimum moves in a maze, degrees of separation in a social graph, or level-order tree serialization all map naturally to BFS. (When edges have varying weights, upgrade to Dijkstra or A*.)
  • Pick DFS for structure, cycles, and combinations: Topological sorting of build dependencies, detecting circular imports, walking nested file trees, and constraint-solving puzzles are cleanest with DFS.
  • Avoid two classic bugs: In BFS, mark nodes visited when enqueuing (not when dequeuing) to prevent exponential duplicate entries. In DFS, switch from recursion to an explicit stack when graph depth could exceed the runtime's call-stack limit.

Notable Examples

  • BFS: Unweighted grid pathfinding in games, LinkedIn connection-degree calculation, and peer-to-peer network discovery.
  • DFS: Module dependency resolution in bundlers (Vite/Webpack), recursive directory and DOM traversal, and cycle detection in package managers.
  • Backtracking solvers: Sudoku, N-Queens, and regex engines combining DFS with pruning.

Practical Code Snippet

Copy and drop straight into your project
graph-traversal.tsTypeScript
export function bfs(graph: Record<string, string[]>, start: string) {  const visited = new Set([start]);  const queue = [start];   while (queue.length > 0) {    const node = queue.shift()!; // FIFO: level by level    for (const next of graph[node] ?? []) {      if (!visited.has(next)) {        visited.add(next);        queue.push(next);      }    }  }  return [...visited];} export function dfs(graph: Record<string, string[]>, node: string, visited = new Set<string>()) {  visited.add(node);  for (const next of graph[node] ?? []) {    if (!visited.has(next)) dfs(graph, next, visited);  }  return [...visited];}