8 queens: 16.7 million boards, or 2,056 placements
Suppose you're asked to place n queens on an n Ć n board so that none of them attacks another.
I'd guess most people's first program picks n squares out of the n² available and then checks whether the result works. You can improve that slightly, because two queens in the same row always attack each other, so you'd pick one column for each row and check afterwards.
However, both versions build complete boards before judging them. Backtracking checks each queen at the moment it's placed and abandons a board as soon as it's clear it can't work.
| n | Any n squares | One per row, then check | Queens placed by backtracking | Solutions |
|---|---|---|---|---|
| 4 | 1,820 | 256 | 16 | 2 |
| 6 | 1,947,792 | 46,656 | 152 | 4 |
| 8 | 4,426,165,368 | 16,777,216 | 2,056 | 92 |
You'll notice the difference isn't a constant factor. A partial board with two queens already attacking each other can never be completed, so every possible completion of it gets skipped at the moment the conflict appears.
def n_queens(n):
cols, diag1, diag2 = set(), set(), set()
count = 0
def place(row):
nonlocal count
if row == n:
count += 1
return
for c in range(n):
if c in cols or row - c in diag1 or row + c in diag2:
continue # attacked: prune
cols.add(c); diag1.add(row - c); diag2.add(row + c)
place(row + 1)
cols.remove(c); diag1.remove(row - c); diag2.remove(row + c) # undo
place(0)
return count
n_queens(8) # 92
Choose, explore, undo
Backtracking makes one decision at a time, and after each decision it asks whether the partial solution can still be completed. If it can't, you undo that decision and try the next option, and if it can you go one level deeper.
In my experience how well it runs comes down to three things.
- You'd decide the most constrained thing first (for queens that's the rows in order),
- you'd detect failure as early as you possibly can,
- and you'd undo exactly, which means the state after an undo has to equal the state before the choice.
I'd say most backtracking bugs I've seen are an undo that restores almost everything but not quite.
Sorting the input is often what makes early failure detectable. Here are the subsets of [3, 5, 6] that might sum to 9, where the sorted order lets you stop as soon as something is too large (since nothing later in the list can fit either).
- Partial subset
[3], Sum3, What happensgo deeper - Partial subset
[3, 5], Sum8, What happensadding 6 would make 14; the list is sorted, so nothing later fits either. Prune - Partial subset
[3, 6], Sum9, What happensa solution - Partial subset
[5], Sum5, What happensadding 6 would make 11. Prune - Partial subset
[6], Sum6, What happensnothing left to add
When the search should become a table
If you only need to know how many solutions there are, and different paths reach the same situation, then the search starts repeating itself. Counting the plus and minus sign patterns that hit a target is probably the usual example, because many prefixes reach the same running total at the same index and the number of ways to finish doesn't depend on how you got there.
If you memoise on the index and the running total the exponential search becomes a table.
I generally ask two questions of any search, namely whether I can spot failure earlier and whether states repeat. A yes to the first usually makes the backtracking faster, and a yes to the second usually means it's really dynamic programming.
I've put the board version, with one move at a time, on my site in case it's useful: https://academicquant.co.uk/coding-backtracking-why?utm_source=devto&utm_medium=post&utm_campaign=devto-backtracking-why
Comments
No comments yet. Start the discussion.