Backtracking is a depth-first search technique that builds a solution one decision at a time and abandons (backtracks from) a partial solution as soon as it cannot lead to a valid result. In C you implement it with a recursive function that chooses an option, checks constraints, recurses to the next decision, and then undoes the choice. The N-Queens and subset-sum programs below show both patterns.
Backtracking suits problems where the answer is a sequence of choices under constraints: puzzles, permutations, combinations, scheduling and constraint satisfaction. Its running time is still exponential in the worst case; the saving comes from pruning whole branches early.
Almost every backtracking function has the same shape:
The un-choose step is what makes it backtracking rather than plain recursion. With a global array that is overwritten by the next iteration, as in the N-Queens code below, it can be implicit. With a counter, a visited flag or a growing list, you must reverse the change explicitly.
The goal is to place N queens on an N by N board so that no two share a row, column or diagonal. Because each row holds exactly one queen, the state is an array col_of_row[r]. Two queens at (r, c) and (row, col) share a diagonal when r - c == row - col or r + c == row + col.
Given a list of positive integers and a target, decide whether some subset adds up to the target. At each index you either include the value or skip it. Prune when the remaining target goes negative. This shows backtracking with an explicit un-choose step (picked[index] = false).
Compile and run with gcc -std=c17 -Wall -Wextra -O2 bt.c -o bt:
A 6 by 6 board has exactly 4 solutions; the program prints the first it finds. The subset result depends on the search order: it finds 3 + 4 + 2 = 9 first because it tries to include earlier elements before skipping them.
is_safe check cuts this drastically, though the worst case remains exponential.true up the call chain so the search stops at the first solution.Brute force generates every complete candidate and tests it. Backtracking tests partial candidates and drops a whole branch the moment a constraint fails.
Backtracking enumerates choices and does not reuse results. Dynamic programming stores answers to overlapping subproblems; use it when the same subproblem appears many times.
Use it for combinatorial problems where you build a solution step by step, such as N-Queens, Sudoku, permutations and maze paths, and where early constraints can prune the search.
It finds every valid solution if you let it finish. For an optimisation problem you keep the best one seen, and branch and bound can prune further.
Backtracking is a recursive search that chooses, explores and un-chooses, pruning any branch that violates a constraint. In C, keep the state in arrays, test the goal first, check constraints before recursing, and undo every change before trying the next candidate. N-Queens and subset sum are the standard exercises for learning it.