Python 3D Academyবাংলা

Pruning: N-Queens and combination sum

🌍 In real life. You have notes of 2, 3 and 5 taka and want to pay exactly 8 taka. Trying every pile of notes, even piles worth 50 taka, would be silly: the moment your pile is worth more than 8, adding more notes can only make it worse, so you stop and take a note back. And if a 3 taka note already overshoots, a 5 taka note will too, so you don't even try it.

The same thinking solves a famous chess puzzle: put n queens on an n × n board so that no two attack each other (no two in the same row, column or diagonal). Placing a queen on a square that is already attacked can never lead to an answer, so you never place one there. Cutting off hopeless choices early like this is called pruning, and it is what makes backtracking fast enough to use.

The idea in one sentence: prune a branch the moment you can prove that nothing below it can be an answer, so the search never spends time inside it.

Its words:

  • prune (cut): skip a choice, and everything that would follow it, without exploring it
  • bound: a test that proves a branch is hopeless (the total is already over the target)
  • sorted candidates: if they are sorted, one candidate that is too big means every later one is too big too, so the loop can break
  • attacked: in N-Queens, a square in the same column or diagonal as a queen already placed

Combination sum, step by step:

  1. sort the candidates
  2. if the total equals the target, collect the path
  3. for each candidate from start: if adding it overshoots, break (cut it and every bigger one)
  4. otherwise choose it, explore with the same start (it may be used again), then undo

Red ✗ nodes are cut branches: whole parts of the tree that are never explored:

N-Queens, step by step: go row by row, one queen per row. In row r, for each column c: if the square is attacked, cut it; otherwise place the queen, explore row r + 1, and undo. A queen at (r, c) attacks its column c, the diagonal where every square has the same r − c, and the other diagonal where every square has the same r + c, so three sets answer "is it attacked?" in one step each. When a row has no safe square left, the queen above was a wrong turn and is undone:

Why it is correct. Pruning never loses an answer, because a branch is only cut when it provably can't contain one: with positive candidates the total only grows, so once it is over the target, everything below is over too; and with sorted candidates, if c overshoots, every later candidate is at least c and overshoots as well. In N-Queens a queen on an attacked square already breaks the rule, and more queens can't un-break it. Everything that is not cut is explored exactly as before, so the answers are the same; only the wasted work disappears.

What it costs, by counting. The worst case is still exponential, but pruning cuts the real work enormously:

  • 8 queens, trying every way to put one queen in each row: 8⁸ = 16,777,216 boards
  • with pruning: 15,720 squares tried in all, to find all 92 solutions

That is over a thousand times less work. For combination sum, pruning means the search never goes deeper than target ÷ (smallest candidate) choices, and never explores a branch past the target.

def combination_sum(candidates, target):
    candidates = sorted(candidates)
    out, path = [], []
    def go(start, total):
        if total == target:
            out.append(path[:])
            return
        for i in range(start, len(candidates)):
            c = candidates[i]
            if total + c > target:
                break                  # prune: this and every bigger one is too much
            path.append(c)
            go(i, total + c)           # i, not i + 1: c may be used again
            path.pop()
    go(0, 0)
    return out

def n_queens(n):
    cols, diag1, diag2 = set(), set(), set()
    def go(r):
        if r == n:
            return 1                   # every row has a queen
        count = 0
        for c in range(n):
            if c in cols or r - c in diag1 or r + c in diag2:
                continue               # prune: attacked, don't even try
            cols.add(c); diag1.add(r - c); diag2.add(r + c)
            count += go(r + 1)
            cols.discard(c); diag1.discard(r - c); diag2.discard(r + c)
        return count
    return go(0)

print(combination_sum([5, 2, 3], 8))
print([n_queens(n) for n in range(1, 9)])

Mistakes and edge cases.

  • break without sorting first: a bigger candidate can come before a smaller one, so the break cuts answers that were fine
  • go(i + 1, …) in combination sum: each candidate can then be used only once, and answers like [2, 2, 2, 2] are lost
  • checking only one diagonal: queens on the other diagonal attack each other, and the count is too big
  • forgetting to undo the sets: a column stays "taken" after its queen is removed, and solutions are missed
  • a target no pile can make: the answer is []; and no answer exists for 2 or 3 queens, while 1 queen on a 1 × 1 board is one solution

Quiz

  1. What does this print?

    def combination_sum(candidates, target):
        candidates = sorted(candidates)
        out, path = [], []
        def go(start, total):
            if total == target:
                out.append(path[:])
                return
            for i in range(start, len(candidates)):
                c = candidates[i]
                if total + c > target:
                    break                  # prune: this and every bigger one is too much
                path.append(c)
                go(i, total + c)           # i, not i + 1: c may be used again
                path.pop()
        go(0, 0)
        return out
    
    print(combination_sum([3, 2], 6))
  2. Why may combination sum break out of its loop as soon as one candidate overshoots?

    • The candidates are sorted, so every later candidate is at least as big and overshoots too
    • Because one answer is enough
    • Because the target was reached
  3. Two queens at (1, 3) and (3, 1). Do they attack each other?

    • Yes: r + c is 4 for both, so they share a diagonal
    • No: different rows and different columns
    • Only if r − c is the same
  4. n_queens(4) should be 2, but this gives more. Which line is wrong?

    def n_queens(n):
        cols, diag1 = set(), set()
        def go(r):
            if r == n:
                return 1
            count = 0
            for c in range(n):
                if c in cols or r - c in diag1:
                    continue
                cols.add(c); diag1.add(r - c)
                count += go(r + 1)
                cols.discard(c); diag1.discard(r - c)
            return count
        return go(0)
  5. Finding all 92 solutions to 8-queens, row by row: about how many squares does pruning try?

    • About 16 thousand, instead of 16 million boards without pruning
    • About 16 million either way
    • Exactly 92

Coding tasks

  1. Write combination_sum(candidates, target): the candidates are different positive whole numbers (in any order), each usable any number of times. Return every list of candidates that adds up to target, each list from small to big, listed in the order backtracking finds them after sorting the candidates. Prune: stop as soon as a candidate would go over the target.

  2. Write n_queens(n): how many ways n queens can be placed on an n × n board with no two attacking each other. Place one queen per row, and prune: never place a queen on a square whose column or either diagonal is already taken.