Skip to content
← All Comparisons

BFS vs DFS

Quick Answer

Use BFS when you need the shortest path in an unweighted graph, level-order traversal, or anything that requires processing nodes layer by layer. Use DFS when you need exhaustive search, path detection, cycle detection, topological sort, or backtracking.

Side-by-Side Comparison

AspectBFSDFS
Data structureQueue (FIFO)Stack / recursion (LIFO)
Traversal orderLevel by level (breadth-first)As deep as possible first (depth-first)
Space complexityO(w) where w = max width of the levelO(h) where h = height/depth
Shortest path?Yes (unweighted graphs)No (finds a path, not necessarily shortest)
When optimalTarget is close to the root / startTarget is deep or solution needs full paths
Time complexityO(V + E)O(V + E)
ImplementationIterative (queue-based loop)Recursive or iterative (explicit stack)

When to Use BFS

When to Use DFS

Key Differences

Memory usage

BFS can use significantly more memory on wide graphs because the queue holds the entire frontier (up to the width of the widest level). DFS only stores the current path, so it uses O(h) space. For balanced trees, BFS uses O(n/2) while DFS uses O(log n).

Completeness

BFS is complete — it will always find the solution if one exists (and the shortest one at that). DFS can get stuck in infinite branches in graphs with cycles unless you track visited nodes.

Trees vs Graphs

For trees, the choice depends on whether you need level-order processing (BFS) or root-to-leaf paths (DFS). For graphs, the deciding factor is usually whether you need shortest path (BFS) or need to explore every possibility (DFS).

How to Decide

  1. Does the problem ask for "shortest", "minimum steps", or "fewest moves"? Use BFS.
  2. Does the problem ask for "all paths", "all combinations", or "exists a path"? Use DFS.
  3. Is it a tree level-order problem (zigzag, right view)? Use BFS.
  4. Do you need to process nodes bottom-up or compute subtree properties? Use DFS.
  5. Is the graph very wide but shallow? Consider DFS to save memory.
  6. Is the graph very deep but narrow? Consider BFS to save memory and avoid stack overflow.

Example Problems

BFS

  • 1.Binary Tree Level Order Traversal — Process each level as a group using a queue.
  • 2.Word Ladder — Find the shortest transformation sequence from one word to another, changing one letter at a time.
  • 3.Rotting Oranges — Multi-source BFS from all rotten oranges simultaneously to find the minimum time.

DFS

  • 1.Number of Islands — Flood fill: for each unvisited land cell, DFS to mark the entire connected island.
  • 2.Path Sum II — Find all root-to-leaf paths that sum to a target by building paths recursively.
  • 3.Course Schedule — Detect cycles in a directed graph using DFS with three-color marking.