Placing N queens on an N × N board so that none attack each other is the most famous backtracking example. A queen attacks along its row, its column and its two diagonals. It is a constraint problem: several rules must be satisfied at once.
Representing a solution
Since each row has exactly one queen, you do not need a board: a list where position f stores the column of the queen of row f is enough. So [2, 4, 1, 3] means: row 0 → column 2, row 1 → column 4, etc. With this representation they cannot attack along a row.
Checking whether a cell is safe
A queen at (row, col) attacks another at (f, c) if they are in the same column or if the difference in columns equals the difference in rows (same diagonal).
def is_safe(columns, row, col):
for f in range(len(columns)):
c = columns[f]
if c == col or abs(c - col) == row - f:
return False
return True
print(is_safe([2], 1, 3)) # False (diagonal)
print(is_safe([2], 1, 4)) # True
The backtracking
def solve(n, columns, solutions):
row = len(columns)
if row == n:
solutions.append(list(columns))
return
for col in range(1, n + 1):
if is_safe(columns, row, col): # pruning
columns.append(col)
solve(n, columns, solutions)
columns.pop()
solutions = []
solve(4, [], solutions)
print(solutions) # [[2, 4, 1, 3], [3, 1, 4, 2]]
The same for 8 queens gives 92 solutions. Without pruning you would have to look at 8⁸ = 16 777 216 placements; with pruning a few thousand are visited. Practise in The N queens problem.
solutions = []
solve(8, [], solutions)
print(len(solutions)) # 92
print(solutions[0]) # [1, 5, 8, 6, 3, 7, 2, 4]
Drawing a solution
def draw(columns):
n = len(columns)
for c in columns:
row = ""
for j in range(1, n + 1):
row += "Q " if j == c else ". "
print(row.strip())
draw([2, 4, 1, 3])
# . Q . .
# . . . Q
# Q . . .
# . . Q .
Other constraint problems
The same structure works for many problems: choose a value for each "variable" so that all the rules are met. What changes is what a variable is, which values it can take and what is "valid".
| Problem | Variables | Values | Constraint |
|---|---|---|---|
| N queens | one per row | column 1..N | they do not attack |
| Map coloring | regions | colors 1..K | neighbors with different colors |
| Sudoku | empty cells | digits 1..9 | no repeats in row, column or block |
| Timetables | classes | time slots | no clash of teacher or room |
Coloring a map
A color is assigned to each region in order. A color is valid if no already colored neighbor uses it. If later on you cannot continue, you go back: the color is deleted and the next one is tried.
def is_valid(neighbors, assigned, node, color):
for v in neighbors[node]:
if assigned.get(v) == color:
return False
return True
def color_map(neighbors, k, n, node, assigned):
if node > n:
return True # all colored
for color in range(1, k + 1):
if is_valid(neighbors, assigned, node, color):
assigned[node] = color
if color_map(neighbors, k, n, node + 1, assigned):
return True
del assigned[node] # undo
return False
neighbors = {1: [2, 3], 2: [1, 3, 4], 3: [1, 2, 4], 4: [2, 3]}
assigned = {}
print(color_map(neighbors, 3, 4, 1, assigned), assigned)
# True {1: 1, 2: 2, 3: 3, 4: 1}
Notice that this function returns True as soon as it finds a solution, and that signal propagates upwards to stop the rest. It is the "find one solution" variant as opposed to "find all". You practise it in Color a map.