Backtracking: try, and step back
How do you find your way out of a maze? You set off, and at every fork you take one path. If you end up in a dead end, you go back to the last fork and try the next path there. That is backtracking. Brute force from lesson 35 builds every possibility to the end and only then checks it; backtracking gives up on a path as soon as it is clear that it cannot lead to the goal.
The most famous example is the queens puzzle: place n queens on an n×n chessboard so that none can take another. A queen moves along rows, columns and diagonals – so no row, no column and no diagonal may hold more than one. First by brute force, for 4 queens. Each row gets one queen; cols[r] says in which column the queen of row r stands:
rows = (0...4).to_a
solutions = rows.permutation.select do |cols|
rows.combination(2).none? do |a, b|
(a - b).abs == (cols[a] - cols[b]).abs # diagonal?
end
end
p rows.permutation.size
solutionsBecause a permutation uses every column exactly once, two queens never share a row or a column – only the diagonals are left to check: two queens are on a diagonal when they are as many rows apart as columns. abs makes a number positive, (-2).abs is 2. Two solutions among 24 candidates.
For 8 queens there would already be 40,320 candidates, for 12 almost 480 million. Backtracking would rather place the queens row by row and check at once whether the new queen is safe. queens are the columns of the queens already standing; the new one goes into the next row:
def safe?(queens, col)
row = queens.size # the next free row
queens.each_with_index do |c, r|
return false if c == col # the same column
return false if row - r == (col - c).abs # diagonal
end
true
end
p safe?([1, 3], 0)
safe?([1, 3], 2)In row 2, column 0 the new queen is safe; in column 2 it would stand diagonally next to the queen in row 1. Now the backtracking itself, as a recursion: if n queens are standing, the solution is found. Otherwise try every safe column in the next row: place the queen (<<), search on with the rest – and if that leads nowhere, take the queen away again (pop takes out the last element) and try the next column. If no column fits at all, it is a dead end: nil, and the call above tries on. The puts line shows every try, indented by its row:
def queens(n, placed = [])
return placed if placed.size == n # all standing: solved
(0...n).each do |col|
next unless safe?(placed, col)
puts " " * placed.size + "row #{placed.size}: column #{col}"
placed << col # try
solution = queens(n, placed)
return solution if solution
placed.pop # take it back
end
nil # dead end
end
queens(4)Read the trace from the top: the first queen stands in column 0, the second in column 2 – and in row 2 nothing is safe any more. Back! The second queen moves on to column 3, the third finds column 1, but there is no room for the fourth again. Back, and back once more: with the first queen in column 0 it doesn't work at all. With column 1 it then works in one go. 8 queens placed instead of 24 finished boards checked. And if there is no solution at all, the search goes back all the way to the start – three queens on a 3×3 board:
queens(3)Every path ends in a dead end, so queens(3) returns nil. A solution as a list of columns is hard to read – let's draw the board: Q for a queen, . for an empty square. With 5 queens, by the way, the very first try goes straight through; the trace has only five lines:
def board(solution)
solution.each do |col|
squares = (0...solution.size).map { |c| c == col ? "Q" : "." }
puts squares.join(" ")
end
end
board(queens(5))And how many solutions are there? Instead of stopping at the first, all_queens searches on and counts. The difference is in two lines: a finished board counts 1, and after every try the queen is always taken back:
def all_queens(n, placed = [])
return 1 if placed.size == n # one more solution
count = 0
(0...n).each do |col|
next unless safe?(placed, col)
placed << col
count += all_queens(n, placed)
placed.pop
end
count
end
p all_queens(4)
all_queens(5)2 and 10 solutions. Try all_queens(6) as well: six queens have only 4 – fewer than five! – and 8 queens have 92. The recipe for every backtracking: 1. Is the solution complete? Then return it. 2. Otherwise try every possibility for the next step that is still allowed: put it in, search on, and if that fails, take it back. 3. If nothing fits, return nil – then the step before tries its next possibility. The sooner you notice that a path fails, the more work you save.
fill_basket(packets, target): it returns a selection of the packets that weighs exactly target together, or nil if there is none. With backtracking: try it with the first packet and search on for the rest; if that doesn't work, search on without the first packet. Give up on a path as soon as the target is exceeded.# def fill_basket(packets, target)
# return [] if target == 0 # done: nothing is missing
# return nil if target < 0 || packets.empty? # too heavy, or none left
# ... # with the first packet: fill_basket(the rest, target - the first)
# ... # if that fails: fill_basket(the rest, target), without the first
# end
# fill_basket([8, 6, 7, 5, 3], 16)
allowed? checks already. Write solve_sudoku(grid): find the first empty square – if there is none, the grid is solved, return it. Otherwise try 1 to 4: if the number is allowed, write it in and solve on; if that doesn't work, set the square back to 0. If no number fits, return nil.puzzle = [
[0, 0, 0, 3],
[0, 4, 0, 0],
[0, 0, 3, 0],
[2, 0, 0, 0]
]
def allowed?(grid, r, c, n)
return false if grid[r].include?(n) # the row
return false if grid.any? { |row| row[c] == n } # the column
r0 = r / 2 * 2 # the 2×2 box
c0 = c / 2 * 2
box = [grid[r0][c0], grid[r0][c0 + 1],
grid[r0 + 1][c0], grid[r0 + 1][c0 + 1]]
!box.include?(n)
end
# def solve_sudoku(grid)
# r = ... # the first row with a 0 – none: solved, return grid
# c = ... # the column of the 0 in that row
# ... # try 1 to 4: write it in, solve on, take it back
# end
# solve_sudoku(puzzle)