Skip to content
Visual explainer 3h to learn 4 steps

Constraint search & pruning

Solve N-Queens, Sudoku and word search efficiently by pruning invalid branches early.

By Invicly Tech, , in Data Structures & Algorithms. About 13 minutes to read.

Topic 46 of 54

In short

Constraint problems like N-Queens, Sudoku and word search are backtracking with strong pruning. Before exploring a choice you check it against the constraints and abandon whole branches that cannot succeed. Good pruning and fast constraint checks make exponential searches practical.

Explained simply

Some puzzles have rules that every answer must follow. In Sudoku, each row, column and 3 x 3 box must contain the digits 1 to 9 once. In N-Queens, no two queens on a chessboard may attack each other. These rules are called constraints.

You can solve such puzzles by backtracking: fill one spot, move to the next, and undo when you get stuck. The key trick is to check the rules immediately after every move. If a move already breaks a rule, there is no point exploring anything after it.

Throwing away a whole branch of choices at once is called pruning, like cutting a dead branch off a tree. Good pruning is the difference between a solver that finishes in milliseconds and one that would run for years.

Three things make pruning work well: checking rules in O(1) with sets or bitmasks, choosing the hardest spot to fill first, and remembering to undo every change when you step back.

Press Play on a diagram to walk through it one step at a time.

FlowPlacing queens row by row
  1. 1
    Row r

    Try each column c.

  2. 2
    Check sets

    Column, r-c and r+c diagonals free?

  3. 3
    Place

    Add to sets, recurse to row r+1.

  4. 4
    Remove

    Backtrack and try the next column.

  5. 5
    Row n

    All queens placed: record solution.

MapPruning techniques
Cut the search
  • Feasibility
    • Reject a move that breaks a rule
    • Check with sets or bitmasks in O(1)
  • Bounds
    • Stop if it cannot beat the best so far
    • Branch and bound
  • Ordering
    • Most constrained variable first
    • Most promising value first
  • Symmetry
    • Skip mirror images
    • Try only one empty bucket
  • Memoisation
    • Repeated sub-states become DP
CompareThree classic constraint searches
N-Queens
  • One queen per row
  • Sets: columns, r - c, r + c
  • Count or list placements
Sudoku
  • 81 cells, digits 1 to 9
  • Sets per row, column and box
  • MRV makes it fast
Word search
  • DFS from each start cell
  • Mark and restore cells
  • Trie for many words

In depth

N-Queens: why r - c and r + c

Place one queen per row, so rows never clash. Columns are easy: keep a set of used columns. For diagonals, notice that along a down-right diagonal both row and column grow by 1, so r - c stays the same. Along a down-left diagonal, r + c stays the same. Each diagonal therefore has one number, and a set lookup checks it in O(1).

The counts are well known: n = 1 has 1 solution, n = 2 and 3 have none, n = 4 has 2, n = 8 has 92 and n = 10 has 724. Symmetry can halve the work: count solutions with the first queen in the left half of row 0, double it, and handle the middle column separately when n is odd.

For more speed, replace the three sets with three integers used as bitmasks. Then the free squares in a row are one expression: ~(cols | d1 | d2) & ((1 << n) - 1).

  • Column: c; diagonals: r - c and r + c
  • Solutions: n=4 has 2, n=8 has 92, n=10 has 724
  • Bitmask version: shift the diagonal masks by one each row

Word search on a grid

To find a word in a letter grid by moving up, down, left or right without reusing a cell, start a DFS from every cell that matches the first letter. At each step, check bounds and the next letter before going further, which is the pruning. Mark the current cell as used (for example, overwrite it with "#") and put the letter back when the call returns.

The worst case is O(R x C x 4 x 3^(L - 1)) for a word of length L: 4 directions for the first step, then at most 3, since you cannot go back to the cell you came from. Cheap pre-checks help in practice: if the grid has fewer copies of some letter than the word needs, return False at once. If the last letter is rarer than the first, search for the reversed word, so the search fails sooner.

To look for many words at once, put them in a trie and walk the trie during the DFS.

FlowOne DFS step in word search
  1. 1
    Check cell

    In bounds and equals word[i]?

  2. 2
    Mark

    board[r][c] = "#"

  3. 3
    Try neighbours

    Four directions, index i + 1.

  4. 4
    Restore

    Put the letter back.

  5. 5
    Return

    True if any neighbour finished the word.

Sudoku: constant-time checks and the hardest cell first

Keep three lists of sets: digits used in each row, each column and each box. The box of cell (r, c) is r // 3 * 3 + c // 3, a number from 0 to 8. Placing a digit adds it to three sets; undoing removes it from the same three. Checking a digit is three set lookups.

A plain solver fills cells in reading order. A much faster one picks the empty cell with the fewest legal digits each time. This is the minimum remaining values (MRV) heuristic, also called most constrained first. A cell with one option is filled with no guessing, and a cell with zero options proves the current path is dead immediately. Real solvers add constraint propagation: after each placement, remove that digit from the options of every cell it affects, which often solves easy puzzles with no backtracking at all.

  • Box index: r // 3 * 3 + c // 3
  • MRV: branch on the cell with the fewest options
  • Zero options anywhere: backtrack now

A toolbox of pruning ideas

Feasibility checks reject a partial answer that already breaks a rule. Bounds reject a partial answer that cannot beat the best one found so far; this is called branch and bound, and it is how many optimisation searches stay fast. Ordering helps in two ways: branch on the most constrained variable, and try the most promising value first so a good bound appears early.

Symmetry breaking avoids exploring mirror images of the same answer. For example, when splitting numbers into k equal buckets, putting the first number into bucket 1 or bucket 2 is the same thing, so only ever try one empty bucket.

When a search keeps meeting the same sub-state, memoise it, and the backtracking turns into DP. For industrial-size constraint problems, people reach for dedicated solvers such as Google OR-Tools' CP-SAT instead of hand-written search.

Learn it in 4 short steps

About 45m each. Track them with a timer in your plan.

  1. 1
    Solve N-Queens with column and diagonal sets~45m
  2. 2
    Solve word search on a grid~45m
  3. 3
    Write a Sudoku solver~45m
  4. 4
    Prune branches with constraint checks~45m

Key points

  • Worst case is still exponential; pruning reduces the explored part.
  • O(1) constraint checks with sets beat rescanning the board.
  • Choose the most constrained variable first, such as the Sudoku cell with fewest options.
  • Word search marks cells in use and restores them on return.

Key terms

Tap a card to flip it. 0/3 known

Examples

python
def n_queens(n):                  # count solutions
    cols, d1, d2 = set(), set(), set()
    def place(r):
        if r == n: return 1
        count = 0
        for c in range(n):
            if c in cols or r - c in d1 or r + c in d2:
                continue          # prune
            cols.add(c); d1.add(r - c); d2.add(r + c)
            count += place(r + 1)
            cols.remove(c); d1.remove(r - c); d2.remove(r + c)
        return count
    return place(0)

print(n_queens(8))  # 92

Word search

Grid rows ABCE, SFCS, ADEE. Is "ABCCED" there? Start at A (0, 0), go right to B, right to C, down to C, down to E, left to D. Found. "SEE" is found starting at S (1, 3). "ABCB" fails because the only B next to that C is the one already used, which is marked "#" and so does not match. The generator inside any() stops as soon as one direction succeeds.

python
def exist(board, word):
    R, C = len(board), len(board[0])
    def dfs(r, c, i):
        if i == len(word): return True
        if not (0 <= r < R and 0 <= c < C) or board[r][c] != word[i]: return False
        board[r][c] = "#"                         # mark as used
        found = any(dfs(r + dr, c + dc, i + 1) for dr, dc in ((1, 0), (-1, 0), (0, 1), (0, -1)))
        board[r][c] = word[i]                     # restore
        return found
    return any(dfs(r, c, 0) for r in range(R) for c in range(C))

board = [list("ABCE"), list("SFCS"), list("ADEE")]
print(exist(board, "ABCCED"), exist(board, "SEE"), exist(board, "ABCB"))  # True True False

A compact Sudoku solver

The board is 9 lists of 9 characters with "." for empty cells. Step 1: record every given digit in its row, column and box set, and collect the empty cells. Step 2: go(k) fills empty cell k with each digit that is not in its three sets. Step 3: if a later cell gets stuck, undo the digit in the cell and all three sets, then try the next digit. It changes the board in place and returns True when solved. Choosing the next cell by fewest options (MRV) would make it much faster on hard puzzles.

python
def solve_sudoku(b):                          # b: 9 lists of 9 chars, "." = empty
    rows, cols, boxes = [set() for _ in range(9)], [set() for _ in range(9)], [set() for _ in range(9)]
    empty = [(r, c) for r in range(9) for c in range(9) if b[r][c] == "."]
    for r, c in [(r, c) for r in range(9) for c in range(9) if b[r][c] != "."]:
        rows[r].add(b[r][c]); cols[c].add(b[r][c]); boxes[r // 3 * 3 + c // 3].add(b[r][c])
    def go(k):
        if k == len(empty): return True
        r, c = empty[k]; x = r // 3 * 3 + c // 3
        for d in "123456789":
            if d in rows[r] or d in cols[c] or d in boxes[x]: continue
            b[r][c] = d; rows[r].add(d); cols[c].add(d); boxes[x].add(d)
            if go(k + 1): return True
            b[r][c] = "."; rows[r].remove(d); cols[c].remove(d); boxes[x].remove(d)
        return False
    return go(0)

Quick reference

  • Check constraints right after each move, never only when the board is full
  • N-Queens: sets of columns, r - c and r + c give O(1) checks
  • N-Queens counts: n=4 has 2, n=6 has 4, n=8 has 92
  • Sudoku box index: r // 3 * 3 + c // 3
  • MRV: fill the cell with the fewest legal values next
  • Grid DFS: mark the cell, recurse, then restore it
  • Word search worst case: O(R x C x 4 x 3^(L - 1))
  • Repeated sub-states? Memoise and the search becomes DP

Common mistakes

  • Checking constraints only when the board is full.
  • Forgetting to restore a visited cell in grid word search.

Quick quiz

Pick an answer to see if you're right and why.

Question 1

1Queens at (2, 5) and (4, 3). Do they attack each other?

Question 2

2Which box index does Sudoku cell (row 4, column 7) belong to, using r // 3 * 3 + c // 3?

Question 3

3In word search, what happens if you forget to restore the cell after the recursive call?

Question 4

4What is the main idea of the MRV heuristic?

0/4 answered

Practice exercises

Try each one yourself first. Use the hint if you get stuck, then compare with the solution.

  1. Exercise 1easy

    Generate every string of n pairs of balanced parentheses. Example: n = 3 gives 5 strings.

  2. Exercise 2medium

    Count N-Queens solutions using three integer bitmasks instead of sets. Check that n = 8 gives 92.

  3. Exercise 3hard

    Can nums be split into k groups with equal sums? Example: [4, 3, 2, 3, 5, 2, 1], k = 4 is True (5, 1+4, 2+3, 2+3).

Check yourself

Answer in your head, reveal, then be honest with yourself.

Feel confident about this topic?

Frequently asked questions

What is the difference between backtracking and brute force?
Brute force builds every complete candidate and then checks it. Backtracking checks partial candidates and abandons them early, so it usually explores a tiny part of the full space.
How many solutions does the 8-queens puzzle have?
92 solutions in total. Counting rotations and reflections of the board as the same, there are 12 distinct ones.
How do real Sudoku solvers work?
Most combine constraint propagation (removing digits that cannot fit) with backtracking on the cell with the fewest options. Some model the puzzle as exact cover and use Knuth's Dancing Links (Algorithm X).
Is word search with many words just running the single-word search many times?
That works but repeats a lot of work. Putting all words in a trie lets one DFS from each cell follow every word that shares the current prefix.

Go deeper

ShareXLinkedInWhatsApp