Backtracking builds a solution one choice at a time and abandons a path as soon as it cannot lead to a valid answer, then goes back and tries the next option. It is a smart form of brute force that powers puzzle solvers such as Sudoku and N-Queens, as well as generating subsets, permutations and combinations. The pattern is always the same: choose, explore, un-choose.
In this lesson you will learn
- The choose–explore–un-choose pattern
- Generating all subsets with recursion
- Solving the N-Queens puzzle
- Pruning: cutting off hopeless paths early
- How backtracking differs from dynamic programming
Generating All Subsets
#include <stdio.h>
/* Print every subset of {1, 2, 3}: choose or skip each element */
int set[] = {1, 2, 3};
int chosen[3];
int count = 0;
void subsets(int i, int k) {
if (i == 3) {
printf("{ ");
for (int j = 0; j < k; j++) printf("%d ", chosen[j]);
printf("}\n");
count++;
return;
}
chosen[k] = set[i];
subsets(i + 1, k + 1); /* choose set[i] */
subsets(i + 1, k); /* skip set[i] (undo by not counting it) */
}
int main(void) {
subsets(0, 0);
printf("Total subsets: %d\n", count);
return 0;
}
Output
{ 1 2 3 }
{ 1 2 }
{ 1 3 }
{ 1 }
{ 2 3 }
{ 2 }
{ 3 }
{ }
Total subsets: 8
- For each element there are two choices: include it or leave it out. The recursion explores both, giving 2 × 2 × 2 = 8 subsets.
kcounts how many elements are currently chosen. The “skip” call passes the samek, so the element written tochosen[k]is simply overwritten later. That is the un-choose step.- The calls form a binary decision tree with 2n leaves, so listing all subsets is unavoidably O(2n).
N-Queens: Backtracking with Pruning
Place N queens on an N × N chessboard so that no two attack each other: no shared row, column or diagonal.
#include <stdio.h>
#include <stdlib.h>
#define N 6
int col[N]; /* col[r] = column of the queen in row r */
int solutions = 0;
int safe(int r, int c) {
for (int i = 0; i < r; i++) {
if (col[i] == c) return 0; /* same column */
if (abs(col[i] - c) == r - i) return 0; /* same diagonal */
}
return 1;
}
void place(int r) {
if (r == N) {
if (++solutions == 1) { /* print the first one */
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) printf(col[i] == j ? "Q " : ". ");
printf("\n");
}
}
return;
}
for (int c = 0; c < N; c++) {
if (safe(r, c)) {
col[r] = c; /* choose */
place(r + 1); /* explore */
} /* un-choose happens by overwriting col[r] */
}
}
int main(void) {
place(0);
printf("Solutions for %d queens: %d\n", N, solutions);
return 0;
}
Output
. Q . . . .
. . . Q . .
. . . . . Q
Q . . . . .
. . Q . . .
. . . . Q .
Solutions for 6 queens: 4
- One queen goes in each row, so
col[r]fully describes a board, and rows can never clash. safe()checks the queens already placed: same column, or same diagonal when the column difference equals the row difference.- Pruning is what makes backtracking practical: a column is only tried if it is safe now, so whole branches of impossible boards are never explored. Trying every arrangement of one queen per row would mean checking 66 = 46,656 boards.
- When a row has no safe column, the function returns, and the previous row moves its queen to the next column: the “back” in backtracking.
- The 6 × 6 board has exactly 4 solutions; the classic 8 × 8 board has 92.
The General Template
void backtrack(state) {
if (state is a complete solution) {
record it;
return;
}
for (each choice available in this state) {
if (choice is valid) { /* prune invalid choices early */
make the choice; /* choose */
backtrack(new state); /* explore */
undo the choice; /* un-choose */
}
}
}
Backtracking vs Dynamic Programming
| Backtracking | Dynamic programming | |
|---|---|---|
| Goal | List or find solutions satisfying constraints | Count or optimise over choices |
| Repeated subproblems | Usually not reused | Stored and reused |
| Typical time | Exponential, reduced by pruning | Polynomial in the table size |
| Examples | N-Queens, Sudoku, permutations | Knapsack, edit distance, coin change |
Common Mistakes
- Forgetting to undo a choice, so state from one branch leaks into the next.
- Checking validity only at the end instead of pruning early, which makes the search explode.
- Missing or wrong base cases, giving infinite recursion or missed solutions.
- Printing duplicate solutions when the input has repeated values; sort first and skip equal choices at the same level.
Practice Exercises
Exercise 1. Print all permutations of “ABC”.
Show answer
void permute(char s[], int i, int n) {
if (i == n) { printf("%s\n", s); return; }
for (int j = i; j < n; j++) {
char t = s[i]; s[i] = s[j]; s[j] = t; /* choose */
permute(s, i + 1, n); /* explore */
t = s[i]; s[i] = s[j]; s[j] = t; /* un-choose */
}
}
/* char s[] = "ABC"; permute(s, 0, 3); prints 6 lines */
Exercise 2. Change the subset program to print only the subsets whose elements add up to 3.
Show answer
Pass the running sum as a parameter, print when i == 3 and the sum equals 3, and prune by returning early whenever the sum already exceeds 3. The answer is {1, 2} and {3}.
Frequently Asked Questions
Is backtracking the same as recursion?
Backtracking is a strategy that is usually written with recursion. Not all recursion is backtracking: computing a factorial recurses but never tries alternatives.
How is a Sudoku solver built with backtracking?
Find an empty cell, try digits 1 to 9 that do not clash with the row, column or 3 × 3 box, recurse to the next empty cell, and clear the cell again if no digit leads to a solution.
Summary
- Backtracking explores choices recursively: choose, explore, un-choose.
- Pruning invalid partial solutions early keeps the search manageable.
- It solves constraint puzzles and generates subsets and permutations.
- Use dynamic programming when subproblems repeat and you need an optimum.
Next: Doubly Linked List in C.
