Backtracking in Python
Backtracking is a general algorithmic technique that incrementally builds candidates to
a solution and abandons ("backtracks") as soon as it determines that the candidate cannot
possibly be completed to a valid solution.
It is often used for problems involving searching through all possible configurations,
such as puzzles, combinatorics, and constraint satisfaction problems.
1. Basic Idea
- Choose an option.
- Recurse to explore further.
- If the choice leads to a solution, record it.
- If the choice doesn't lead to a solution, undo (backtrack) and try another option.
2. General Backtracking Template
Example:
def backtrack(path, options):
if is_solution(path):
record_solution(path)
return
for option in options:
if is_valid(option, path):
path.append(option)
backtrack(path, remaining_options(option))
path.pop() # backtrack
3. Example: N-Queens Problem
Place N queens on an NxN chessboard so that no two queens threaten each other.
def solve_n_queens(n):
board = [-1] * n
solutions = []
def is_safe(row, col):
for r in range(row):
if board[r] == col or abs(board[r] - col) == abs(r - row):
return False
return True
def backtrack(row):
if row == n:
solutions.append(board[:])
return
for col in range(n):
if is_safe(row, col):
board[row] = col
backtrack(row + 1)
board[row] = -1
backtrack(0)
return solutions
4. Common Applications
- Solving puzzles like Sudoku, N-Queens, Crosswords
- Generating permutations and combinations
- Solving mazes
- Word search problems
5. Pros & Cons
Advantages:
- Elegant and simple to implement
- Works well for constraint satisfaction problems
Disadvantages:
- May be slow for large search spaces
- Needs careful pruning for efficiency