Dataslope logoDataslope

Backtracking

Learn choose-explore-unchoose search, pruning, and classic backtracking problems in C++

Backtracking builds a solution incrementally and abandons a candidate as soon as it cannot become valid. The template is choose → explore → un-choose.

Backtracking is disciplined recursion

Recursion calls itself; backtracking also deliberately undoes choices and prunes impossible branches.

Permutations

Code Block
C++ 20 (202002L)

Subsets

Include/exclude recursion visits both decisions for each element.

Code Block
C++ 20 (202002L)

Bitmask iteration is deterministic and iterative.

Code Block
C++ 20 (202002L)

N-Queens

Place one queen per row. Columns and diagonals prune invalid placements.

Code Block
C++ 20 (202002L)

Sudoku solver

Try digits 1 through 9 in the next empty cell, recurse, then undo if it fails.

Code Block
C++ 20 (202002L)

Mark a cell visited, search neighbors, then unmark it.

Code Block
C++ 20 (202002L)

Pruning techniques

Check constraints before recursing, reject partial states early, and try promising branches first. Backtracking differs from plain recursion because it explicitly manages partial choices and undoes them.

Challenge
C++ 20 (202002L)
Generate all subsets

Implement std::vector<std::vector<int>> subsets(const std::vector<int>& nums). Use deterministic bitmask order from 0 to 2^n-1 so stdout matches exactly.

Challenge
C++ 20 (202002L)
N-Queens count

Implement int countNQueens(int n). The driver prints counts for n=1..6.

Challenge
C++ 20 (202002L)
Word search

Implement bool exist(std::vector<std::vector<char>>& board, const std::string& word).

QuestionSelect one

What is the classic backtracking pattern?

Sort -> scan -> stop.

Choose -> explore -> un-choose.

Hash -> lookup -> return.

Push all nodes into a queue.

QuestionSelect one

What is pruning?

Rejecting a partial solution before exploring all descendants.

Printing every solution twice.

Removing all recursion.

Sorting output only.

QuestionSelect one

Why unmark a grid cell in word search?

Other paths may need to use it later.

To sort the board.

To make DFS iterative.

To avoid including headers.

On this page