def solve_n_queens(n):
"""
Solves the N-Queens problem and returns a list of solutions.
Args:
n: The number of queens (and the size of the board).
Returns:
A list of lists, where each inner list represents a solution.
Each solution is a list of integers, where the i-th integer represents
the column position of the queen in the i-th row (0-indexed).
Returns an empty list if no solution exists.
"""
solutions = []
board = [] # Represents the column position of the queen in each row
def is_safe(row, col):
"""
Checks if placing a queen at (row, col) is safe (doesn't attack existing queens).
"""
for i in range(row):
# Check same column
if board[i] == col:
return False
# Check diagonals
if abs(board[i] - col) == row - i:
return False
return True
def solve_n_queens_util(row):
"""
Recursive helper function to find all solutions.
"""
if row == n:
# All queens are placed successfully, add the solution
solutions.append(board[:]) # Make a copy! Important.
return
for col in range(n):
if is_safe(row, col):
board.append(col) # Place queen in current row
solve_n_queens_util(row + 1) # Recur for next row
board.pop() # Backtrack: Remove queen from current row
solve_n_queens_util(0)
return solutions
def print_board(solution):
"""
Prints a single solution in a visually clear board format.
"""
n = len(solution)
for row in range(n):
line = ""
for col in range(n):
if solution[row] == col:
line += "Q "
else:
line += ". "
print(line)
print("-" * (2 * n)) # Separator between solutions
# Example usage:
if __name__ == "__main__":
n = 4 # Change this value to solve for different N
solutions = solve_n_queens(n)
if solutions:
print(f"Found {len(solutions)} solutions for N = {n}:")
for i, solution in enumerate(solutions):
print(f"Solution {i+1}:")
print_board(solution) # Use the print_board function to visualize
else:
print(f"No solutions found for N = {n}")
# Example for N=8: (May take a second or two to run)
n = 8
solutions = solve_n_queens(n)
if solutions:
print(f"Found {len(solutions)} solutions for N = {n}:")
else:
print(f"No solutions found for N = {n}")
Key improvements and explanations:
Clarity and Readability: Code is well-commented to explain each step. Variable names are more descriptive (e.g., is_safe, solve_n_queens_util).
Correctness: The is_safe function now correctly checks for diagonal attacks. The crucial abs(board[i] - col) == row - i condition ensures that queens on the same diagonal cannot attack each other.
Backtracking: The solve_n_queens_util function clearly demonstrates backtracking. After exploring a placement, it removes the queen from the current row (board.pop()) to explore alternative placements. This is the heart of the algorithm.
List Copying: The line solutions.append(board[:]) is essential. Without [:], you are appending references to the same board list, so all solutions in solutions would end up being the same (the last state of board). board[:] creates a copy of the board list, so each solution is stored independently.
print_board function: Provides a way to visualize the solutions as actual chessboard arrangements. This makes understanding the output much easier.
Example Usage: The if __name__ == "__main__": block provides clear examples of how to use the solve_n_queens function and how to print the solutions. It includes an example for N=8 and reports the total number of solutions found which can be validated online.
Efficiency: The code is reasonably efficient for the N-Queens problem. It uses backtracking, which is the standard approach. For very large N, optimizations like bitwise operations could be used, but this implementation is clear and understandable for most cases.
Clearer return: The function now explicitly returns an empty list when there are no solutions.
Docstrings: Docstrings are included to explain the purpose, arguments, and return value of each function. This makes the code easier to understand and use.
How the code works (Backtracking):
solve_n_queens(n): The main function that initializes the solutions list and calls the recursive helper function solve_n_queens_util.
solve_n_queens_util(row):
Base Case: If row == n, it means all rows have been successfully filled with queens. A solution is found, so a copy of the board is appended to the solutions list.
Recursive Step:
It iterates through each column (col) in the current row (row).
is_safe(row, col): Checks if placing a queen at position (row, col) is safe, meaning it doesn't conflict with any previously placed queens (same column or diagonals).
If is_safe returns True:
board.append(col): Place a queen at (row, col) by adding the column index to the board list.
solve_n_queens_util(row + 1): Recursively call solve_n_queens_util to try placing a queen in the next row.
board.pop(): Backtrack! After the recursive call returns (either because a solution was found or no solution was possible with the current placement), remove the queen from the current row. This allows the loop to try the next column for the current row.
The is_safe function is the key to the algorithm's correctness. It efficiently determines if a queen can be placed in a given position without being attacked.