Skip to content
← All Comparisons

Backtracking vs DFS

Quick Answer

Use DFS when you only need to explore or find a single path (e.g., path exists, connected components, cycle detection). Use Backtracking when you must enumerate all valid solutions and need to undo choices to try alternatives (e.g., all permutations, all combinations, N-Queens).

Side-by-Side Comparison

AspectDFSBacktracking
Core mechanismExplore and move forward onlyExplore, then undo to try alternatives
State modificationUsually immutable or copy-on-writeMutate state, then restore on backtrack
GoalFind one path, detect cycle, count componentsEnumerate all valid solutions
Typical problemsPath exists, number of islands, cycle detectionAll permutations, subsets, N-Queens, Sudoku
Early terminationOften yes (stop when target found)Usually no (must explore all branches)
Constraint handlingPrune invalid branches; no undo neededPrune and undo to try other valid choices
ImplementationVisit, recurse, return; no explicit undoChoose, recurse, undo (pop/restore), try next

Decision Framework

  1. Does the problem ask for "all" solutions (all paths, all combinations, all permutations)? Use Backtracking.
  2. Does the problem ask "does a path exist" or "how many components"? Plain DFS is enough.
  3. Do you need to share mutable state across branches (e.g., a board, a path array)? Use Backtracking with undo.
  4. Can you pass state forward as copies (e.g., path + [node])? DFS without backtracking may suffice.
  5. Is it a constraint satisfaction problem (N-Queens, Sudoku)? Backtracking with place-and-undo.
  6. Is it a graph/tree traversal with no need to enumerate all valid configurations? Use DFS.

Example Problems

DFS (no backtracking needed)

  • 1.Number of Islands — Flood fill; mark visited, no need to undo.
  • 2.Path Sum — Check if any root-to-leaf path sums to target; pass sum forward.
  • 3.Course Schedule — Cycle detection; no enumeration of all valid orderings.
  • 4.Max Area of Island — Count cells in each component; no undo.

Backtracking (undo required)

  • 1.Permutations — Enumerate all orderings; swap, recurse, swap back.
  • 2.Subsets — Include/exclude each element; push, recurse, pop.
  • 3.N-Queens — Place queen, recurse, remove queen to try next column.
  • 4.Word Search — Mark cell, recurse, unmark to allow reuse in other paths.