Backtracking Algorithm in AI
With Example Problem: N-Queens
What is Backtracking Algorithm?
• - Solves problems recursively
• - Builds solution step by step
• - Removes those that fail to satisfy constraints
• - Depth-First Search (DFS) approach
Key Features of Backtracking
• - Solves Constraint Satisfaction Problems (CSP)
• - Explores all possibilities
• - Uses recursion and backtracking
• - Avoids invalid solutions
Applications of Backtracking
• - Sudoku Solver
• - Crossword Puzzle
• - Map Coloring
• - N-Queens Problem
• - Word Search
• - Maze Solving
Example: 4-Queens Problem
• - Place 4 queens on a 4x4 board
• - No two queens threaten each other
• - No same row, column, or diagonal
Step-by-Step Solution
(Backtracking)
• - Place queen in Row 1 → Column 1
• - Row 2 → Try all columns → Place at Column
3
• - Row 3 → Place at Column 4
• - Row 4 → No safe column → Backtrack
• - Try different positions until solution found
Final Solution for 4-Queens
• - Row 1 → Column 2
• - Row 2 → Column 4
• - Row 3 → Column 1
• - Row 4 → Column 3
• - ✅ All queens placed safely
Backtracking Pseudo-code
• def solve(board, row):
• if row >= N:
• print(board)
• return True
• for col in range(N):
• if is_safe(board, row, col):
• board[row][col] = 1
• if solve(board, row + 1):
Advantages and Disadvantages
• - ✅ Simple and effective for small problems
• - ❌ Time-consuming for large problems
• - ❌ May explore many failed paths
• - ✅ Can be optimized with heuristics