The user wants a solution to the N-queens problem.
I need to provide an implementation. Python is a good default choice for clarity, but I might offer a C++ or Java version if requested. Since the user didn't specify, I'll stick to Python for its readability.
What is the N-queens problem?
The problem is to place N chess queens on an N×N chessboard so that no two queens threaten each other. This means no two queens can share the same:
Row
Column
Diagonal
Approaches:
Brute Force: Generate all configurations. Too slow (O(NN) or O(N!) depending on implementation).
Backtracking: This is the standard approach. Place a queen in a valid spot, move to the next row, and try to place the next queen. If we reach a state where no valid spot exists in a row, backtrack to the previous row and move that queen.
Bitmasks: An optimization of backtracking for higher N.
Symmetry: We can optimize by only iterating through the first half of the columns for the first row.
Core Algorithm (Backtracking):
State: We need to track the board or just the positions of the queens. An array queens of size N is sufficient, where queens[i] = j means the queen in row i is at column j.
Validation (is_safe function):
When placing a queen at (row, col), check all previous queens (i, queens[i]) where i < row.
Condition 1: queens[i] == col (Column check - actually, if we iterate row by row, we don't strictly need to check rows, but columns must be unique).
If row == N, we found a solution. Add to list of solutions.
Iterate col from 0 to N−1.
If is_safe(row, col):
queens[row] = col
solve(row + 1)
(Implicit backtracking: queens[row] will be overwritten or ignored on return)
Optimization (Sets/Arrays):
Instead of an O(N)is_safe check every time, we can maintain sets for occupied columns and diagonals.
cols: Set of occupied columns.
pos_diag: Set of occupied positive diagonals (row−col is constant).
neg_diag: Set of occupied negative diagonals (row+col is constant).
This makes the check O(1).
Formatting the Output:
Users usually want to see the board. I should provide a helper function to visualize the solution (e.g., using 'Q' and '.'). I should also allow the user to define N.
Structure of the Code:
Class NQueens or a function solve_n_queens(n).
backtrack function.
print_board function.
Example usage.
Let's draft the Python code using the set optimization for efficiency.
Input:n
Output: List of solutions (where a solution is a list of strings representing rows).
Sets:col, pos_diag, neg_diag.
pos_diag calculation: r−c. (e.g., top-left to bottom-right). Actually, standard convention usually maps specific constants. Let's verify: (0,0)→0, (. Correct.
Refining the implementation:
I will provide a clean, recursive solution with sets for validity checking.
python
def solveNQueens(n):
solutions = []
board = [['.' for _ in range(n)] for _ in range(n)] # Or just keep track of positions
# Actually, storing just column indices in a list 'queens' is more memory efficient than the full board string matrix during recursion.
queens = [-1] * n
cols = set()
pos_diag = set() # r + c
neg_diag = set() # r - c
def backtrack(r):
if r == n:
# Create board representation
solution = []
for i in range(n):
row = ["."] * n
row[queens[i]] = "Q"
solution.append("".join(row))
solutions.append(solution)
return
for c in range(n):
# Check validity
if c in cols or (r + c) in pos_diag or (r - c) in neg_diag:
continue
# Place queen
queens[r] = c
cols.add(c)
pos_diag.add(r + c)
neg_diag.add(r - c)
backtrack(r + 1)
# Remove queen (backtrack)
cols.remove(c)
pos_diag.remove(r + c)
neg_diag.remove(r - c)
# queens[r] reset happens implicitly next loop or is irrelevant after return
backtrack(0)
return solutions
This looks correct and standard. I should present this clearly.
Additional considerations:
What if N is very small? (e.g., 2 or 3). No solutions. The code handles it.
What if N is large? Python has a recursion limit, but for standard N (e.g., 8 or 9), it's fine. N=20 might be slow without bitmasking, but the set approach is reasonably fast (O time, but efficient constant factors).
Final Plan:
Briefly explain the problem and the backtracking approach.
Provide the Python code.
Explain the specific optimizations used (tracking columns and diagonals in sets).
Show an example of how to run it and what the output looks like.
I will write the code to print the solutions nicely.
python
import sys
def print_solutions(solutions):
for sol in solutions:
for row in sol:
print(row)
print("-" * len(sol[0]))
Wait, N can be N. The print logic is generic.
Let's double check the diagonal math.
If I am at (r,c).
Positive diagonal (down-right): next is (r+1,c+1). sum is . Diff is .
Wait.
Let's stick to one definition.
:
.
.
.
This represents the diagonal from top-left to bottom-right.
r+c:
(0,1)→1.
(1,0)→1.
This represents the diagonal from top-right to bottom-left.
So checking r - c and r + c covers all diagonal cases.
The solution will be provided in Python. I'll include a main block to run it.
Alternative: Bitwise
Bitwise is faster but harder to explain to a general audience. Sets are "Pythonic" and readable. I will stick to sets.
Code Structure:
python
def solve_n_queens(n):
def create_board(state):
board = []
for row in state:
board.append("".join(row))
return board
def backtrack(row, diagonals, anti_diagonals, cols, state):
# Base case - N queens have been placed
if row == n:
ans.append(create_board(state))
return
for col in range(n):
curr_diagonal = row - col
curr_anti_diagonal = row + col
# If the queen is not placeable
if col in cols or curr_diagonal in diagonals or curr_anti_diagonal in anti_diagonals:
continue
# "Add" the queen to the board
cols.add(col)
diagonals.add(curr_diagonal)
anti_diagonals.add(curr_anti_diagonal)
state[row][col] = 'Q'
# Move on to the next row
backtrack(row + 1, diagonals, anti_diagonals, cols, state)
# "Remove" the queen from the board since we have already
# explored all valid paths using the above function call
cols.remove(col)
diagonals.remove(curr_diagonal)
anti_diagonals.remove(curr_anti_diagonal)
state[row][col] = '.'
ans = []
empty_board = [['.' for _ in range(n)] for _ in range(n)]
backtrack(0, set(), set(), set(), empty_board)
return ans
This uses a full state board matrix state during recursion, which is slightly less efficient memory-wise than just a list of column indices, but easier to visualize for the user because create_board is straightforward. However, modifying state[row][col] repeatedly involves string/list manipulation.
Actually, using a list ['.', '.', '.', '.'] is mutable.
Let's stick to the slightly more efficient "list of queens" approach for the internal state, but build the strings at the end. It demonstrates better engineering practices.
Internal state: positions (list of ints, length N). positions[r] = c.
When r == N:
Convert positions to board strings.
Let's write the response.
Here is a clean, efficient implementation of the N-Queens problem in Python using backtracking.
The Approach
To solve the problem, we place queens one row at a time. Since two queens cannot share the same row, we only need to decide which column to place the queen in for the current row.
We use three sets to track which columns and diagonals are currently under attack to ensure valid placement in O(1) time:
Cols: Tracks occupied columns.
Positive Diagonals: Tracks diagonals where row + col is constant.
Negative Diagonals: Tracks diagonals where row - col is constant.
Python Implementation
python
def solve_n_queens(n):
"""
Solves the N-Queens problem and returns all distinct board configurations.
"""
solutions = []
# We only need a 1D array to store state:
1
,
1
)
→
0
neg_diag calculation: r+c. (e.g., top-right to bottom-left). (0,n−1)→n−1, (1,n−2)→n−1. Correct.