Pruning
- Algorithms course
- Intermediate
- Lesson 71/80
- 4 min
Cut dead branches early to save time.
Pruning
Pruning cuts infeasible branches early, reducing returns. It speeds up backtracking.
Good pruning can turn an exponential algorithm polynomial-like; this is why it matters.
Pruning shrinks the search space and makes a big difference in practice; especially for N-queens.
Early check
Pruning is a check before taking a step. If infeasible the branch is never expanded.
In N-queens, same-column or diagonal checks are examples; a queen placement is rejected early.
Early checks prevent needless recursive calls and save time.
Practice Count N-queens
Write count_n_queens(n). Count placements of n non-attacking queens on an n×n board with backtracking. Print 2 with print(count_n_queens(4)).
Starter code
def count_n_queens(n):
# Count queensSample solution
def count_n_queens(n):
# Count queens
def safe(cols, row, col):
for r in range(row):
c = cols[r]
if c == col or abs(c - col) == row - r:
return False
return True
count = 0
def backtrack(row, cols):
nonlocal count
if row == n:
count += 1
return
for col in range(n):
if safe(cols, row, col):
cols[row] = col
backtrack(row + 1, cols)
backtrack(0, [0] * n)
return count
print(count_n_queens(4))Expected output
2
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Pruning: match the terms
| Term | Meaning |
|---|---|
prune |
Prune |
early check |
Early check |
branch |
Branch |
feasible |
Feasible |
2 When is pruning done?
- At the start
- Before a step Correct answer
- At the result
- After a step
Explanation: Before a step.
3 Pruning condition
if not ____:
if not feasible:
Explanation: feasible is right.