N-queens and pruning
لم يُترجم بعد؛ يُعرض باللغة الإنجليزية
عن هذا الدرس
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.
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)
اقرأ الدرس خطوة بخطوة
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)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]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-3Skip 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 diagonalA 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 3Backtrack 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, ·]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 FalseMove 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, ·, ·]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 256Why 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
أسئلة سريعة: 5
اختر إجابة واحدة لكل سؤال. يمكنك تغيير اختياراتك قبل التحقق منها.
01A queen stands at row 0, column 1. Which square in row 2 does it attack?
Same column means column 1. Same diagonal means the columns differ by the rows apart, 2 − 0 = 2: column 1 − 2 = −1 (off the board) or 1 + 2 = 3. Column 3 is on its diagonal, and column 1 (not offered) shares its column.
02Why can the program store the whole board as one list cols of length N?
Two queens in one row would attack each other, and N queens fill N rows, so each row holds exactly one. That also removes the row rule from safe(): only columns and diagonals need checking.
03In the 4-queens run, row 2 has no safe square after queens at columns 0 and 2. What does place(2) do?
The loop runs out, so place(2) returns False. Control goes back to place(1), whose loop continues with column 3. That return to the caller is the backtrack.
04What is pruning in this search?
When safe(r, c) is False, the loop never calls place(r + 1) for that square. Every board below it, all the ways to fill the remaining rows, is cut off in one go.
05For 8 queens, how many one-per-row boards would a blind search try, and how many safe() checks does backtracking need to find all 92 solutions?
One queen per row gives 8⁸ = 16,777,216 boards. Backtracking makes 15,720 safe() checks and places 2,056 queens to find all 92 solutions. 256 and 26 are the 4-queens numbers.
المسرد
- N-queens puzzle
- Place N chess queens on an N × N board so that no two share a row, a column or a diagonal.
- Backtracking
- A search that builds an answer one choice at a time and undoes the last choice when it cannot be completed.
- Pruning
- Cutting off a branch of the search as soon as it breaks a rule, so nothing below it is explored.
- Partial solution
- An answer that is only partly built, here the queens in the rows filled so far.
- Dead end
- A point where no choice is left that keeps the partial solution valid. The search must back up.
- Search tree
- All the partial solutions, linked from each one to the ones it can grow into. Backtracking walks it depth first.
- safe(r, c)
- The check in this lesson: True if no queen in the rows above r shares column c or a diagonal with square (r, c).
الملاحظات والمصادر
- The code is real Python 3. The whole program is N = 4, cols = [0] * N, safe(r, c) and place(r); place(0) returns True and leaves cols = [1, 3, 0, 2]. The search stops at the first solution; the other one for N = 4 is its mirror image, [2, 0, 3, 1].
- Cells for rows below the current row show a dot. In the real list they still hold old values, but safe() never reads them: it only looks at rows 0 to r − 1.
- The N = 8 counts (15,720 safe() checks, 2,056 queens placed, 92 solutions) come from running this program with N = 8 and no early return, and match the 15,720 placements examined by Wirth's program and the 92 solutions listed for the eight queens puzzle.
- "Board 115": listing every one-per-row board in order, [0,0,0,0], [0,0,0,1], ..., the solution [1, 3, 0, 2] comes at position 1·64 + 3·16 + 0·4 + 2 + 1 = 115, and each of those boards would need a full check.
- Pruning does not change the worst-case growth of N-queens search, which still grows faster than any polynomial; it cuts the constant so far that N = 8 finishes instantly. Counting all solutions for large N remains hard: OEIS A000170 lists the known values.
- Sedgewick and Wayne, Introduction to Programming in Java, §2.3 Recursion (N-queens exercises)
- Sedgewick and Wayne, Queens.java: N-queens by recursion and backtracking
- Eight queens puzzle (92 solutions, 8⁸ one-per-row boards, 15,720 placements examined)
- OEIS A000170: number of ways of placing n nonattacking queens on an n × n board
- Backtracking
- MIT 6.006 Introduction to Algorithms (Spring 2020), Lecture 15: Dynamic Programming, Part 1
- Cormen, Leiserson, Rivest and Stein, Introduction to Algorithms, 4th ed. (MIT Press, 2022)
- Python documentation: built-in functions (range, abs)
اختبار يتاح بعد الخطوة الأخيرة.