Five search problems where every choice rules out others. The move: keep the constraints as bit sets or marks, pick the variable with the fewest options, and end a branch the moment nothing can fit.
You work on a robot floor planner, a banner layout tool and a puzzle app. The five problems on this street place things so that no two clash, or walk a path that never reuses a cell. A queen takes a column and two diagonals, and a digit takes a place in a row, a column and a box.
The Academy lesson Backtracking with pruning already solves queens with a test before each choice. This street makes that test cheap, chooses the order of the choices, and counts instead of listing.
| Problem | One choice is | What it rules out | What is counted |
|---|---|---|---|
| Place the queens | a column for a robot in this row | its column and two diagonals, and the pillars | every full layout |
| Count the queen placements | a column, or no banner in this row | its column and two diagonals | layouts of exactly k banners |
| Solve the sudoku | a digit for the emptiest cell | the digit in its row, column and box | solutions, but never more than 2 |
| Best route to a door | the next cell with items | the cells already on the route | the largest total that ends at a door |
| Words in a letter grid | the next neighbouring letter | the cells already used, and letters no word has | the words that can be traced |
Exercise · Predict the output: Six robots on a six by six floor. Three integers hold the used columns and the two diagonals as bit sets. The code counts the layouts of 6 robots on a 6 by 6 floor, one in each row. What does it print?
n = 6
def place(row, cols, diag1, diag2):
if row == n:
return 1
count = 0
for c in range(n):
if cols >> c & 1 or diag1 >> (row + c) & 1 or diag2 >> (row - c + n - 1) & 1:
continue
count += place(row + 1, cols | 1 << c, diag1 | 1 << (row + c), diag2 | 1 << (row - c + n - 1))
return count
print(place(0, 0, 0, 0))The move has three parts, and each one removes work from the Academy version.
First, keep each constraint as a bit set, an integer whose bit i says that item i is taken. A choice adds one bit, and the call below receives the new integer. The old integer is still in the caller, so there is nothing to undo.
Second, choose the variable with the fewest options. Third, end a branch the moment some variable has none, or when the room left is smaller than the work left.
| Problem | The bit sets | The variable chosen | A branch ends when |
|---|---|---|---|
| Place the queens | columns, diagonal one, diagonal two | the next row, in order | no column is free in the row |
| Count the queen placements | the same three | the next row, to take or skip | rows left are fewer than banners left |
| Solve the sudoku | rows, columns, boxes | the empty cell with the fewest digits | a cell has no digit left |
Each call holds bit sets that match exactly the choices made so far. A branch ends the moment some variable has no option left, or when the room left cannot hold the work left.
Only the sudoku needs a free choice of variable, because queens fill one row at a time. A cell with one option is forced. A cell with none is a dead end that the search finds at once.
Fill the cell with the fewest options first: a forced cell is free, and a cell with none ends the branch at once.
Exercise · Find the bug: The undo forgets a diagonal. This counts the layouts of n robots on an n by n floor with three lists of marks. It marks the column and both diagonals, then undoes the marks after the call. Which line is wrong?
def count_layouts(n):
cols = [False] * n
diag1 = [False] * (2 * n - 1)
diag2 = [False] * (2 * n - 1)
def place(row):
if row == n:
return 1
count = 0
for c in range(n):
if cols[c] or diag1[row + c] or diag2[row - c + n - 1]:
continue
cols[c] = diag1[row + c] = diag2[row - c + n - 1] = True
count += place(row + 1)
cols[c] = diag1[row + c] = False
return count
return place(0)The Academy lessons Backtracking with pruning and Subsets and permutations teach choose, explore and undo, with a test before each choice. This street does not teach that again. It changes three things.
The test costs one step. Three integers replace three lists, and a pillar is one more bit per row. On an empty 11 by 11 floor the search makes 166,926 calls, while 11 factorial orders would be 39,916,800.
A choice may be to skip. A row may stay empty when you place k banners on an 8 by 8 grid. With k = 7, ending a branch when the rows left are fewer than the banners left gives 26,611 calls. Without that test the search makes 182,085.
For n = 10 and k = 9 the numbers are 650,161 and 11,185,043.
The order of the variables matters. On a classic sudoku with 51 empty cells, filling cells in reading order makes 4,632 calls. Choosing the cell with the fewest options makes 52. On a second puzzle with 54 empty cells the numbers are 23,502 and 104.
Counting every solution when only 0, 1 or many is asked wastes calls. Stop at the second solution.
Exercise · Put it in order: The most constrained cell. Each number in masks is a bit set of the digits already used around one empty cell, with bit 0 for digit 1. Arrange the lines into a function that returns the index of the cell with the fewest digits left, the first one on a tie, or -1 when there are no cells.
def most_constrained(masks):
best, best_count = -1, 10
for i, mask in enumerate(masks):
options = 9 - bin(mask).count("1")
if options < best_count:
best, best_count = i, options
return best
if options > best_count:Solve them in this order. The first walks a grid with marks. The next three use bit sets and pillars, a choice to skip, and the cell with the fewest options. The last walks a grid with a trie.
Before you code each problem, write two lines: what a choice rules out, and which variable you choose next. If the second line is "the next one in order", check whether another order ends dead branches sooner.
Give each problem about 30 minutes. Spend the first five on the two lines, and say them aloud as you would to an interviewer. Then write the number of calls you expect for a small input, and check it by running the code.
Three edge cases return on every rung. A floor with a pillar in every cell has zero layouts. A given digit may already break a rule, and the answer is then 0. A request for more banners than rows has no layout.
When a solution fails, check the undo before the loop. Most wrong answers on this street come from a mark that is never cleared, or from a prune that removes a branch that could succeed.
Checkpoint · Constraint search
Q1/5 How does the code know in one step that a cell is free for a robot?
Answer: B
One bit set holds the used columns and two hold the diagonals. Testing a cell is three bit reads, whatever the number of robots.
Q2/5 Marks are kept in lists that every call shares. After the recursive call, which marks must be cleared?
Answer: C
A mark that stays blocks cells in all the later branches, so layouts are lost. Bit sets passed by value need no undo.
Q3/5 Counting layouts of 7 banners on an 8 by 8 grid, why end a branch when the rows left are fewer than the banners left?
Answer: B
A branch that cannot place enough banners can never succeed, so ending it removes only wasted calls.
Q4/5 Why fill the sudoku cell with the fewest options first?
Answer: B
On a classic puzzle with 51 empty cells it needs 52 calls instead of 4,632 in reading order.
Q5/5 You must report 0, 1 or "many" solutions for a sudoku. When can the search stop?
Answer: B
Two solutions already answer "more than one", so counting further would only waste calls. A count of 0 or 1 needs the whole search.
Review cards from this lesson.
A few questions, then explain the idea back in your own words. Your tutor marks it. Quiz and explain back.