The N-Queens problem is a classic combinatorial challenge that involves placing N queens on an N×N chessboard such that no two queens threaten each other. A queen can attack any piece that shares the same row, column, or diagonal. Therefore, the goal is to find all possible configurations of N queens on the board where none of them are in a position to capture another.
This problem is often used as an example to demonstrate backtracking algorithms due to its recursive nature and constraint satisfaction requirements. In this tutorial, we will explore how to solve the N-Queens problem using backtracking, providing detailed explanations, code examples, and best practices.
Find all possible configurations where N queens are placed on an N×N chessboard without any of them being able to capture another.
Backtracking is a general algorithm for finding all (or some) solutions to computational problems, notably constraint satisfaction problems, that incrementally builds candidates to the solutions and abandons a candidate ("backtracks") as soon as it determines that the candidate cannot possibly be completed to a valid solution.
We will implement the N-Queens problem using Python. The code will include functions to check if a queen can be placed safely on the board, to solve the problem recursively, and to print all solutions.
def is_safe(board, row, col):
# Check this row on left side
for i in range(col):
if board[row][i] == 1:
return False
# Check upper diagonal on left side
for i, j in zip(range(row, -1, -1), range(col, -1, -1)):
if board[i][j] == 1:
return False
# Check lower diagonal on left side
for i, j in zip(range(row, len(board), 1), range(col, -1, -1)):
if board[i][j] == 1:
return False
return True
def solve_n_queens_util(board, col):
# base case: If all queens are placed then return true
if col >= len(board):
return True
# Consider this column and try placing this queen in all rows one by one
for i in range(len(board)):
if is_safe(board, i, col):
# Place this queen in board[i][col]
board[i][col] = 1
# recur to place rest of the queens
if solve_n_queens_util(board, col + 1):
return True
# If placing queen in board[i][col] doesn't lead to a solution,
# then remove queen from board[i][col]
board[i][col] = 0
# if the queen cannot be placed in any row in this column col then return false
return False
def solve_n_queens(n):
board = [[0 for _ in range(n)] for _ in range(n)]
if not solve_n_queens_util(board, 0):
print("Solution does not exist")
return False
# Print the solution
for row in board:
print(" ".join(str(x) for x in row))
return True
# Example usage
n = 4
solve_n_queens(n)
is_safe(board, row, col): This function checks if it's safe to place a queen at board[row][col]. It verifies that no other queens are in the same row, column, or diagonal.
solve_n_queens_util(board, col): This is a recursive utility function that attempts to place queens one by one in different columns. If placing a queen leads to an invalid configuration, it backtracks and tries another position.
solve_n_queens(n): This function initializes the board and calls the utility function to solve the N-Queens problem. It also prints the solution if found.
Optimization: The above implementation can be optimized by using additional data structures to keep track of columns and diagonals that are already occupied, reducing the number of checks needed in is_safe.
Iterative Approach: For very large values of N, consider using an iterative approach with a stack to avoid deep recursion issues.
Parallelization: If you need to find all solutions for large N, consider parallelizing the search space across multiple threads or processes.
Testing: Ensure thorough testing with different values of N, including edge cases like N=1 and N=2, where no solution exists.
The N-Queens problem is a fascinating example of how backtracking can be applied to solve constraint satisfaction problems. By understanding the constraints and using an efficient backtracking approach, we can find all possible configurations for placing N queens on an N×N chessboard. This tutorial provides a comprehensive guide to solving the N-Queens problem, including code examples and best practices for implementation.
By mastering this problem, you will gain valuable insights into recursive algorithms, constraint satisfaction, and optimization techniques that are applicable in various domains of computer science and software engineering.