def solve_nqueens(n):
"""
Solves the N-Queens problem and returns a list of all possible board configurations
where N queens can be placed on an NxN chessboard without threatening each other.
Args:
n: The size of the chessboard (NxN) and the number of queens to place.
Returns:
A list of lists, where each inner list represents a solution board configuration.
Each configuration is a list of integers, where the integer at index 'i'
represents the column (0-indexed) where the queen is placed in row 'i'.
Returns an empty list if no solution exists.
"""
solutions = [] # To store all valid solutions
def is_safe(board, row, col):
"""
Checks if placing a queen at board[row][col] is safe (not threatened by other queens).
Args:
board: The current state of the chessboard (list of integers representing column placement).
row: The row index to check.
col: The column index to check.
Returns:
True if placing a queen at (row, col) is safe, False otherwise.
"""
# Check in the same column
for prev_row in range(row):
if board[prev_row] == col:
return False
# Check upper left diagonal
for prev_row, prev_col in zip(range(row - 1, -1, -1), range(col - 1, -1, -1)):
if board[prev_row] == prev_col:
return False
# Check upper right diagonal
for prev_row, prev_col in zip(range(row - 1, -1, -1), range(col + 1, n)):
if board[prev_row] == prev_col:
return False
return True
def solve_nqueens_util(board, row):
"""
Recursive utility function to solve N-Queens using backtracking.
Args:
board: The current state of the chessboard (list of integers representing column placement).
row: The current row index being considered.
"""
if row == n:
# Base case: All queens are placed successfully
solutions.append(board[:]) # Add a copy of the board to solutions
return
for col in range(n):
if is_safe(board, row, col):
board[row] = col # Place queen in the current row and column
solve_nqueens_util(board, row + 1) # Recursively solve for the next row
# No explicit backtracking needed here because we are trying different columns
# in the loop. If a path doesn't lead to a solution, the loop continues
# to the next column for the current row.
board = [-1] * n # Initialize board with -1 (no queen placed in each row initially)
solve_nqueens_util(board, 0)
return solutions
def print_board(board_config):
"""
Prints a single N-Queens board configuration in a visually clear format.
Args:
board_config: A list of integers representing a valid board configuration.
"""
n = len(board_config)
for row in range(n):
line = ""
for col in range(n):
if board_config[row] == col:
line += "Q "
else:
line += ". "
print(line)
print("-" * (2 * n)) # Separator between solutions
if __name__ == "__main__":
n = 4 # Change n to solve for different board sizes (e.g., n=8 for the classic 8-Queens problem)
solutions = solve_nqueens(n)
if solutions:
print(f"Solutions for {n}-Queens problem:")
for i, solution in enumerate(solutions):
print(f"Solution {i+1}:")
print_board(solution)
print(f"Total solutions: {len(solutions)}")
else:
print(f"No solution exists for {n}-Queens problem.")
Explanation:
solve_nqueens(n) function:
This is the main function that initiates the N-Queens problem solving.
It initializes an empty list solutions to store all valid board configurations found.
It calls the recursive helper function solve_nqueens_util(board, row) to start the backtracking process.
Finally, it returns the solutions list.
is_safe(board, row, col) function:
This function is crucial for checking if it's safe to place a queen at a particular position (row, col) on the board.
Checks for threats in:
The same column: It iterates through the rows above the current row (prev_row from 0 to row-1) and checks if any queen in those rows is in the same column (board[prev_row] == col).
Upper left diagonal: It iterates diagonally upwards and to the left from (row, col) and checks if any queen exists along this diagonal.
Upper right diagonal: It iterates diagonally upwards and to the right from (row, col) and checks if any queen exists along this diagonal.
Returns True if the position is safe (no threats), and False otherwise.
solve_nqueens_util(board, row) function (Recursive Backtracking):
This is the core recursive function that uses backtracking to explore possible placements of queens.
Base Case:if row == n:
If row reaches n, it means we have successfully placed queens in all n rows without conflicts.
We have found a valid solution. We append a copy of the current board configuration to the solutions list (using board[:] to create a copy, as we don't want to modify the original board in other recursive calls).
The function then returns (backtracks).
Recursive Step:for col in range(n):
It iterates through all columns (col from 0 to n-1) in the current row.
How to run the code:
Save the code as a Python file (e.g., nqueens.py).
Run it from your terminal: python nqueens.py
You can change the value of n in the if __name__ == "__main__": block to solve for different board sizes (e.g., n = 8 for the classic 8-Queens problem).
Key Concepts Used:
Backtracking: A problem-solving technique that explores potential solutions incrementally. If a path leads to a dead end or a conflict, it backtracks to a previous state and tries a different path.
Recursion: The solve_nqueens_util function is recursive, calling itself to solve subproblems (placing queens in subsequent rows).
Constraint Satisfaction: N-Queens is a constraint satisfaction problem where we need to satisfy the constraint that no two queens threaten each other.
Depth-First Search (DFS): Backtracking can be viewed as a form of depth-first search in the space of possible queen placements.
For each column, it checks if placing a queen at (row, col) is safe using the is_safe function.
If it's safe:
board[row] = col: Place the queen in the current row and column by storing the column index in board[row].
solve_nqueens_util(board, row + 1): Recursively call solve_nqueens_util for the next row (row + 1). This means we try to place queens in the remaining rows based on the current placement.
Backtracking (Implicit): If the recursive call solve_nqueens_util(board, row + 1) does not lead to a solution (it returns without finding a solution for the subsequent rows), the for col loop continues to the next column in the current row. This is the backtracking step. We don't need to explicitly "undo" the queen placement in this particular implementation because in the next iteration of the for col loop, we are trying a different column in the same row, effectively overwriting the previous placement in board[row] if necessary.
print_board(board_config) function:
This function is for nicely printing a single board configuration.
It iterates through each row and column of the board.
If board_config[row] == col, it means there's a queen at that position, so it prints "Q ".
Otherwise, it prints ". " (representing an empty square).
It adds a separator line after each printed board for clarity.