ENع
←N-queens
Lesson 45 · Dynamic programming and backtracking

N-queens and pruning

14 min10 steps5 questionsAdvanced
About this lesson

Backtracking builds an answer one choice at a time and throws a partial answer away the moment it breaks a rule. Watch the real search for 4 queens on a 4×4 board, square by square: a short Python function places one queen per row, skips every attacked square, backs up when a row has no safe square, and finds cols = [1, 3, 0, 2] after 26 checks. Then see why that pruning matters even more on an 8×8 board. The lesson "Backtracking: subsets and permutations" introduces the choose, explore, un-choose pattern, and the Software lesson on dynamic programming covers memoisation and tables, the other way to avoid wasted work.

You'll learn to

Tick what you feel confident about. These self-checks do not affect your lesson score.

Fig 45 · Interactive
01 / 10

Four queens, no attacks

Put 4 queens on a 4×4 board so that no two attack each other. A queen attacks along its row, its column and both diagonals. So every row must hold exactly one queen. On an 8×8 board this is the eight queens puzzle.

goal: 4 queens on a 4×4 board, no two in the same
  row, column or diagonal

solutions for N = 4: 2   (for N = 8: 92)
Loading figure…
or ← →
Read the lesson step by step
  1. Four queens, no attacks

    Put 4 queens on a 4×4 board so that no two attack each other. A queen attacks along its row, its column and both diagonals. So every row must hold exactly one queen. On an 8×8 board this is the eight queens puzzle.

    goal: 4 queens on a 4×4 board, no two in the same
      row, column or diagonal
    
    solutions for N = 4: 2   (for N = 8: 92)
  2. One list holds the board

    One queen per row means a list says it all: cols[r] is the column of the queen in row r. Trying every list blindly means 4⁴ = 256 full boards. Backtracking builds the list one row at a time instead.

    cols = [c0, c1, c2, c3]
    cols[r] = column of the queen in row r
    
    blind search: 4 choices per row, 4^4 = 256 boards
    backtracking: one row at a time, test as you go
    
    N = 4
    cols = [0] * N          # cols[r] = column of the queen in row r
    
    def safe(r, c):
        for i in range(r):  # only the rows above r hold queens
            if cols[i] == c or abs(cols[i] - c) == r - i:
                return False
        return True
    
    def place(r):
        if r == N:
            return True
        for c in range(N):
            if safe(r, c):
                cols[r] = c
                if place(r + 1):
                    return True
        return False
    
    print(place(0), cols)   # True [1, 3, 0, 2]
    
  3. The first queen

    place(0) works on row 0. The board is empty, so safe(0, 0) is true and cols[0] = 0. The squares this queen attacks in the rows below are shaded: its column and its diagonal.

    place(0)
      row 0, col 0: safe   → cols[0] = 0
    cols = [0, ·, ·, ·]
    
    attacked below: 1-0 1-1 2-0 2-2 3-0 3-3
  4. Skip what cannot work

    place(1) tries row 1. Column 0 shares a column with the first queen, column 1 a diagonal, so safe() says no and the loop skips them without going deeper. That skip is pruning. Column 2 is safe: cols[1] = 2.

    place(1)
      row 1, col 0: attacked → skip
      row 1, col 1: attacked → skip
      row 1, col 2: safe   → cols[1] = 2
    cols = [0, 2, ·, ·]
    
    safe(r, c) fails when, for a queen (i, q) above:
      q == c            same column
      abs(q - c) == r - i   same diagonal
  5. A dead end

    Row 2: all four squares are attacked. safe() fails four times, the loop runs out and place(2) returns False. No board that starts with queens at columns 0 and 2 is ever built past this row.

    place(2)
      row 2, col 0: attacked → skip
      row 2, col 1: attacked → skip
      row 2, col 2: attacked → skip
      row 2, col 3: attacked → skip
      loop done → return False
    cols = [0, 2, ·, ·]
    
    pruned: the 16 ways to fill rows 2 and 3
  6. Backtrack and try again

    Backtrack: control returns to place(1), whose loop simply moves on. Column 3 is safe, so cols[1] = 3 overwrites the 2. Row 2 now has a safe square at column 1: cols[2] = 1.

    back in place(1)
      row 1, col 3: safe   → cols[1] = 3
    place(2)
      row 2, col 0: attacked → skip
      row 2, col 1: safe   → cols[2] = 1
    cols = [0, 3, 1, ·]
  7. Every branch fails

    Row 3 is fully attacked: dead end. Back in row 2, columns 2 and 3 fail too. Row 1 has no columns left. So no solution starts with a queen in column 0 of row 0.

    place(3)
      row 3, col 0: attacked → skip
      row 3, col 1: attacked → skip
      row 3, col 2: attacked → skip
      row 3, col 3: attacked → skip
      → return False
    back in place(2)
      row 2, col 2: attacked → skip
      row 2, col 3: attacked → skip
      → return False
    place(1): loop done → return False
  8. Move the first queen

    Back at the top, place(0) moves its queen to column 1. Row 1 rejects columns 0, 1 and 2, and takes column 3.

    back in place(0)
      row 0, col 1: safe   → cols[0] = 1
    place(1)
      row 1, col 0: attacked → skip
      row 1, col 1: attacked → skip
      row 1, col 2: attacked → skip
      row 1, col 3: safe   → cols[1] = 3
    cols = [1, 3, ·, ·]
  9. Solved

    Row 2 takes column 0, row 3 takes column 2, and place(4) finds r == N: solved, cols = [1, 3, 0, 2]. That took 26 safe() checks. Trying full boards in order would reach this one only at board 115.

    place(2)
      row 2, col 0: safe   → cols[2] = 0
    place(3)
      row 3, col 0: attacked → skip
      row 3, col 1: attacked → skip
      row 3, col 2: safe   → cols[3] = 2
    place(4): r == N → return True
    cols = [1, 3, 0, 2]
    
    safe() checks: 26
    queens placed: 8
    blind order: board 115 of 256
  10. Why pruning pays

    Pruning pays more as boards grow. 8 queens have 8⁸ = 16,777,216 one-per-row boards. Backtracking finds all 92 solutions after 15,720 safe() checks, because each dead branch is cut the moment its first queen fails.

    N = 8, every solution
      one-per-row boards  8^8 = 16,777,216
      safe() checks       15,720
      queens placed       2,056
      solutions           92

Quiz Unlocks after the last step.