Backtracking

Suppose we need to generate every possible arrangement of five distinct cards. We can choose a card for the first position, then choose one of the remaining cards for the second position, and continue until the arrangement is complete. After recording one arrangement, we return to an earlier choice and try another possibility.

Backtracking is a recursive search that tries available choices, explores the consequences of each choice, and then undoes it. If a partial solution cannot lead to a valid answer, the entire branch can be discarded.

Generating permutations

Consider three distinct cards numbered 1, 2 and 3. We want to generate every possible order.

Choose an unused card for the first position, then an unused card for the second position, and finally the remaining card. When all positions are filled, record the permutation. Return to the previous position, undo its choice, and try the next available card.

Cards 1, 2 and 3 are put into a row of three positions one at a time and taken back from the end; each full row is copied into a list that grows to the 6 orders 1 2 3, 1 3 2, 2 1 3, 2 3 1, 3 1 2, 3 2 1.

Fig. 1. Card 1 stays in the first position while both orders that start with it are written down. It leaves only when positions 2 and 3 have nothing left to try.

This generates all six permutations: 1 2 3, 1 3 2, 2 1 3, 2 3 1, 3 1 2 and 3 2 1. A card already present in the current permutation must not be chosen again.

We can imagine these choices as a search tree. The root represents the empty arrangement. Each node represents the choices made so far, and each edge represents one new choice. For instance, the node 1 has children 1 2 and 1 3, which lead to 1 2 3 and 1 3 2. A complete arrangement is a leaf of this tree. Recursion explores one branch before returning to try another.

The general backtracking pattern is:

  1. If the solution is complete, record it and return.

  2. Iterate over possible choices and skip invalid ones.

  3. Make a choice and recursively explore the next position.

  4. Undo the choice before trying another one.

In pseudocode:

search():
    if solution is complete:
        record solution
        return
    for each available choice:
        if choice is valid:
            make choice
            search()
            undo choice

The important invariant is that after exploring a choice and undoing it, the state used to make further choices must be the same as before that choice.

Implementation

For the cards, a position is a spot in the row and a choice is a card. a[i] is the card in position i, and used[c] is true while card c is in the row. The check is used[c], and taking back is used[c] = false. The function fill(i) chooses a card for position i. The program reads (1\le n\le8) and prints every permutation:

#include <iostream>
#include <vector>
using namespace std;

int n;
vector<int> a;       // a[i] = the card in position i
vector<bool> used;   // used[c] = card c is in the row

void fill(int i) {
    // done? every position has a card
    if (i > n) {
        for (int j = 1; j <= n; j++) cout << a[j] << (j < n ? ' ' : '\n');
        return;
    }
    // try each choice: the cards
    for (int c = 1; c <= n; c++) {
        if (used[c]) continue;     // check it
        a[i] = c;                  // put it
        used[c] = true;
        fill(i + 1);               // go deeper
        used[c] = false;           // take it back
    }
}

int main() {
    cin >> n;
    // initialise: the row is empty
    a.assign(n + 1, 0);
    used.assign(n + 1, false);
    fill(1);
}

On input 3 it prints the six orders of Fig. 1 in lexicographic order. After fill(i + 1) returns, we must set used[c] = false so that later branches can use card c again. We do not need to clear a[i]: only positions before i are considered filled when entering fill(i), and a[i] is overwritten before the next recursive call.

There are complete permutations, and printing each takes time. The total number of nodes in the search tree is \sum_{k=0}^n n!/(n-k)!=O(n!). Each non-leaf call checks up to choices, so this implementation takes O(n\cdot n!) time including output. As discussed in Recursion, the number of calls and their maximum depth are different: at most n+1 calls are active at once. The arrays and call stack use auxiliary memory.

Generating subsets

In Bitmasks, we generated all subsets using an integer mask. We can generate the same subsets recursively. Unlike permutations, here the order of selected cards does not matter. For each card there are two choices: exclude it or include it. Decide cards 1, 2 and 3 in order, then record the selected cards. Undo an inclusion when returning from its recursive call.

The choices form a recursion tree. Each leaf represents a subset.

A binary tree of three levels, drawn left to right: from each circle an edge marked 0 (leave the card) goes up and an edge marked 1 (take it) goes down, deciding cards 1, 2 and 3 in turn; the eight leaves, from top to bottom, are labelled with the subsets empty, 3, 2, 2 3, 1, 1 3, 1 2, 1 2 3, and the path take 1, leave 2, take 3 down to the subset 1 3 is blue.

Fig. 2. Level 1 decides card 1, level 2 card 2, level 3 card 3. Edge 0 leaves the card, edge 1 takes it. The blue path takes card 1, leaves card 2 and takes card 3.

Implementation

For subsets, choose(i) decides card i. It first leaves the card and goes deeper, then takes it, goes deeper again and takes it back. The cards taken so far are kept in a vector chosen. The program reads (1\le n\le20) and prints all subsets:

#include <iostream>
#include <vector>
using namespace std;

int n;
vector<int> chosen;  // the cards taken so far

void choose(int i) {
    // done? every card is decided
    if (i > n) {
        cout << '{';
        for (int j = 0; j < (int)chosen.size(); j++) cout << (j ? " " : "") << chosen[j];
        cout << "}\n";
        return;
    }
    choose(i + 1);         // leave card i
    chosen.push_back(i);   // take card i
    choose(i + 1);
    chosen.pop_back();     // take it back
}

int main() {
    cin >> n;
    choose(1);
}

On input 3 it prints {}, {3}, {2}, {2 3}, {1}, {1 3}, {1 2} and {1 2 3}, the leaves of Fig. 2 from top to bottom.

There are 2^n subsets. Enumerating them takes O(2^n) recursive calls and up to O(n\cdot 2^n) time including output, with auxiliary memory.

Pruning

Return to the shop example from Bitmasks. Five products cost 2 3 5 4 7 coins, and we want all selections with a total price of 11. Suppose we have selected the products costing 2 and 3, and then select the product costing 5. Their total is 10. If we also select the product costing 4, the total becomes 14. Since the remaining prices are non-negative, no continuation of that branch can bring the sum back to 11.

Discarding a branch that cannot lead to a valid solution is called pruning. Instead of building every complete subset and checking its sum at the end, we can stop as soon as the partial sum exceeds the target.

For non-negative prices and a non-negative target T, modify the subset search to maintain the sum as a parameter. Assume price is indexed from 1 and chosen is initially empty. Start with choose(1, 0):

void choose(int i, long long sum) {
    if (sum > T) return;
    if (i > n) {
        if (sum == T) {
            for (int x : chosen) cout << x << ' ';
            cout << '\n';
        }
        return;
    }
    choose(i + 1, sum);
    chosen.push_back(i);
    choose(i + 1, sum + price[i]);
    chosen.pop_back();
}

Here each call has its own sum, but the calls share chosen, so the vector still needs its undo step. With the five products, the valid selections are items 1, 3 and 4, and items 4 and 5. This pruning rule relies on non-negative prices: if later values can be negative, a partial sum above the target might still become equal to it. For example, 12 + (-1) = 11.

Pruning can reduce the actual amount of work without changing the worst-case exponential complexity. Only discard a branch if no extension of its current state can satisfy the problem's requirements.

Choosing exactly k elements

Suppose instead that we need every subset containing exactly of the cards (0\le k\le n). At the start of choose(i), chosen contains the cards already taken and there are n - i + 1 cards still undecided. We can stop if we have already taken too many, or if taking every remaining card would still leave us with too few.

Add these checks before the base case of the original subset function:

int taken = (int)chosen.size();
if (taken > k) return;
if (taken + (n - i + 1) < k) return;

When i > n, no undecided cards remain, so any branch reaching the original printing code must have selected exactly k cards. For example, when choosing two cards out of four, after excluding cards 1, 2 and 3 there is only one undecided card left. That branch cannot contain a solution.

The N-queens problem

We can use the same idea when there are several constraints to check at every step. Put 4 queens on a 4×4 chessboard so that no two of them attack each other. A queen attacks every square in its row, in its column and on both of its diagonals. Row 1 is the top row, and column 1 is on the left.

A 4 by 4 chessboard with a queen, marked Q, in row 2, column 2; the 11 squares it attacks in its row, its column and both diagonals are shaded, and the 4 squares it does not attack are white.

Fig. 3. A queen attacks its row, its column and both diagonals. Can you put 4 queens on the board so that none attacks another?

As in Greedy algorithms, we might try making the first available choice: in each row, put the queen on the first unattacked square. Row 1 gets column 1, and row 2 gets column 3. Now row 3 has no free square. Columns 1 and 3 are below the two queens, and columns 2 and 4 are on the diagonals of the queen in row 2.

A locally valid placement does not guarantee that the rest of the board can be completed. The search must undo an earlier placement and explore other available choices.

Two queens in one row attack each other, and there are 4 queens for 4 rows, so each row holds exactly one queen. The same goes for the columns. So a placement is an order of the columns 1 to 4, one column for each row, just like an order of four cards. List all 24 orders as with the cards, and check the diagonals only when the board is full.

Two 4×4 boards side by side. The left board has queens in columns 1, 2, 3, 4 of rows 1 to 4, and the right board has queens in columns 1, 2, 4, 3. On both boards the queens of rows 1 and 2, which stand on the same diagonal, are outlined in blue.

Fig. 4. Both boards start with columns 1 and 2. Those two queens already attack each other, but checking only full boards builds both boards to the end.

This finds both valid placements, but half of the 24 permutations already violate the diagonal constraint after the first two queens. On a 12×12 board, checking only complete permutations would require considering 12!=479{,}001{,}600 candidates.

Instead, check a square before placing a queen. If it is attacked, skip that choice. If no valid square remains in the current row, return to the previous row and try another column. This is another example of pruning.

On the example: after the queen in row 1, column 1, the square in column 2 of row 2 is rejected at once. Neither board in Fig. 4 is ever built, and no placement is lost: adding more queens never removes an attack, so a board with two queens attacking each other can never be finished. Every other choice is still tried.

Here is the search on the 4×4 board up to its first placement. In each row it tries the columns from left to right.

Backtracking on the 4 by 4 board, from an empty board to the first placement 2 4 1 3, step 1.

The board is empty. The search starts in row 1, column 1.

1/14

Fig. 5. Backtracking on the 4×4 board up to its first placement. The dark blue square is the queen just put down and light blue squares in its row were attacked. A queen with a blue outline is being taken back, and its box turns red. The boxes beside the board list the column of the queen in each row.

The first placement is columns 2, 4, 1 and 3 in rows 1 to 4. The search put down 8 queens to find it and took back 4. Run on, it finds one more placement, columns 3, 1, 4 and 2, the mirror image of the first, and then stops. For the whole board it puts down 16 queens, while checking only full boards puts down 64. On a 12×12 board the gap is much wider: 856,188 queens against 1,302,061,344. These counts measure individual placements made during the search, not the number of complete boards or the total number of operations.

In Fig. 6 we can see the search tree of the whole run. The empty board is on the left, each column of circles to its right is one row, and each circle is one queen put down, branching into the choices tried after it.

Search tree of the 4×4 queens run, drawn left to right: an empty root with four circles to its right for the column of the row-1 queen (1 to 4), each branching into the columns tried in the next row; the paths 2, 4, 1, 3 and 3, 1, 4, 2 are blue and end in green circles, the two placements, and the circles 3 under 1, 2 under 1 then 4, 3 under 4 then 1, and 2 under 4 have a cross because the next row has no free square.

Fig. 6. 16 queens in all. A cross means the next row has no free square.

Implementation

On the board, a position is a row and a choice is a column. Rows and columns are numbered from 1, row 1 at the top, and n is the size of the board. The queen in row r stands in column c.

As with permutations, a function fill(r) tries the possible choices for row r and calls itself for the next row.

Checking diagonals

When we move one square diagonally down and left, the row increases by 1 and the column decreases by 1, so their sum remains unchanged. When we move diagonally down and right, both increase by 1, so their difference remains unchanged.

The board is kept in arrays that all calls share. col[r] is the column of the queen in row r, used to print the placement. Three arrays mark what the queens already attack:

  • usedCol[c] is true if column c has a queen.

  • diag1[r + c]: on a diagonal going down to the left, every square has the same r + c, from 2 to .

  • diag2[r - c + n]: on a diagonal going down to the right, every square has the same r - c, from 1 - n to n - 1. Adding n keeps the index between 1 and 2n - 1, using the same idea as shifting negative keys in Counting sort. Without this offset, a square with c > r would give a negative index.

Two 4 by 4 boards of numbers: on the left each square shows its row plus column, from 2 to 8, and the three squares with 4, on the diagonal going down to the left, are blue; on the right each square shows row minus column plus 4, from 1 to 7, and the four squares with 4, on the main diagonal going down to the right, are blue.

Fig. 7. Left: on a diagonal going down to the left, every square has the same r + c. Right: on a diagonal going down to the right, every square has the same r - c; adding 4 makes the numbers start at 1.

Local variables such as c belong to one call. The arrays don't: what a call writes into them is still there after it returns. So right after the recursive call returns, the program must clear the marks it set. That is the take-back step.

The function follows the same make–explore–undo pattern as the permutation search. This time, a valid choice must pass all three checks: its column and both diagonals must be unoccupied. The marks for all three are set before the recursive call and cleared immediately after it.

The program reads (1\le n\le12) and prints every placement as the columns of rows 1 to n, then the number of placements cnt. With firstOnly set to true it stops after the first placement (see below). For the 4×4 board the input is:

4
#include <iostream>
#include <vector>
using namespace std;

int n, cnt = 0;
bool firstOnly = false;   // set to true to stop at the first placement
vector<int> col;
vector<bool> usedCol, diag1, diag2;

void fill(int r) {
    // done? every row has a queen
    if (r > n) {
        cnt++;
        for (int i = 1; i <= n; i++) cout << col[i] << (i < n ? ' ' : '\n');
        return;
    }
    // try each choice: the columns of row r
    for (int c = 1; c <= n; c++) {
        // check it: skip an attacked square
        if (usedCol[c] || diag1[r + c] || diag2[r - c + n]) continue;
        // put it
        col[r] = c;
        usedCol[c] = diag1[r + c] = diag2[r - c + n] = true;
        // go deeper
        fill(r + 1);
        // take it back
        usedCol[c] = diag1[r + c] = diag2[r - c + n] = false;
        if (firstOnly && cnt > 0) return;   // only needed to stop at the first placement
    }
}

int main() {
    cin >> n;
    // initialise: no queen on the board
    col.assign(n + 1, 0);
    usedCol.assign(n + 1, false);
    diag1.assign(2 * n + 1, false);
    diag2.assign(2 * n + 1, false);
    fill(1);
    cout << cnt << '\n';
}

The output is:

2 4 1 3
3 1 4 2
2

The first two lines describe the valid placements; the final line is their number.

Each check takes time. At each visited partial placement, the loop considers up to columns. There are at most partial placements, so the running time is bounded by O(n\cdot n!), including output. The arrays and recursion stack require auxiliary memory. Pruning can substantially reduce the number of visited states.

Correctness

The search maintains a partial placement with exactly one queen in each previously processed row and no conflicts between those queens. The three mark arrays describe that partial placement. Each accepted choice preserves this property, and undoing it restores the state before the choice.

Consider any valid complete placement. Its next queen is in an unmarked column and on unmarked diagonals, so the search considers that choice and never prunes its branch. Following the same argument for each row, the search reaches that placement. Conversely, a complete placement is printed only when every row has been filled without a conflict, so every printed placement is valid. Since rows are processed in a fixed order and each column is tried once per call, no placement is printed twice.

Stop at the first placement

Some problems want one placement, and printing all of them is a wrong answer there: on input 4 the main program prints two. Set firstOnly to true. The line if (firstOnly && cnt > 0) return; then leaves every loop as soon as one placement is printed, so on input 4 the program prints 2 4 1 3 and then the count 1.

The program clears the marks before returning even in firstOnly mode, maintaining the same state-restoration rule. If the task asks only for a count, omit the placement output and keep counting. If it asks for an optimum, the first valid solution is not necessarily optimal; the search must consider every potentially better solution unless a justified bound allows pruning.

A count of 0 means there is no placement. If the problem requires only the first solution or a specific message when none exists, adjust the output accordingly.

Similar techniques

Recursion provides the mechanism for exploring smaller problems and returning to earlier calls.

Bitmasks can enumerate all subsets without recursion. Backtracking can avoid exploring entire branches when partial choices prove that no valid solution is possible.

Depth-first search also explores deeply before returning. In a usual graph traversal, visited vertices remain marked. When enumerating simple paths instead, marks can be undone on return to allow a vertex to appear in different paths.

Dynamic programming can reuse results when different branches lead to the same remaining subproblem.

Practice

Was this page helpful?