The N-Queens problem is a classic algorithmic problem: placing 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, or diagonal.
I will implement a solution using backtracking, which is a standard approach for this type of constraint satisfaction problem.
Algorithm:
- Create a board representation (e.g., an array where
board[i] represents the column position of the queen in row i).
- Define a function to check if placing a queen at a specific position is "safe" (i.e., it doesn't conflict with previously placed queens).
- Check for column conflicts.
- Check for diagonal conflicts (specifically, if ∣rowcurrent−rowother∣==∣col, they are on the same diagonal).
- Define a recursive function to place queens row by row.
- Iterate through each column in the current row.
- If the position is safe, place the queen.
- Recurse to the next row.
- If the recursion returns
True (solution found), propagate True up.
- Backtrack: Remove the queen and try the next column.
- Print the solution.
I will implement this in Python.
Here is a Python solution using a backtracking algorithm.
The Approach: Backtracking
The core idea is to place queens one row at a time. When we place a queen, we check if it is "safe" (not attacked by any previously placed queen). If it is safe, we move to the next row. If we reach a row where no column is safe, we backtrack to the previous row and move that queen to a new position.
Python Implementation
def print_board(board):
"""
Helper function to print the board matrix.
"""
for row in board:
print(" ".join(row))
print()
def is_safe(board, row, col, n):
"""
Check if it's safe to place a queen at board[row][col].
We only check the left side because we are filling rows from left to right/top to bottom.
"""
# Check this row on left side
for i in range(col):
if board[row][i] == 'Q':
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] == 'Q':
return False
# Check lower diagonal on left side
for i, j in zip(range(row, n, 1), range(col, -1, -1)):
if board[i][j] == 'Q':
return False
return True
def solve_n_queens_util(board, col, n):
"""
Recursive utility function to solve N Queens problem.
"""
# Base case: If all queens are placed, return True
if col >= n:
return True
# Consider this column and try placing this queen in all rows one by one
for i in range(n):
if is_safe(board, i, col, n):
# Place this queen in board[i][col]
board[i][col] = 'Q'
# Recur to place rest of the queens
if solve_n_queens_util(board, col + 1, n):
return True
# If placing queen in board[i][col] doesn't lead to a solution,
# then remove queen from board[i][col] (BACKTRACK)
board[i][col] = '.'
# If the queen can not be placed in any row in this column col
# then return False
return False
def solve_n_queens(n):
"""
Main function to initiate the N-Queens solver.
"""
# Initialize the board with empty spaces ('.' represents empty)
board = [['.' for _ in range(n)] for _ in range(n)]
if not solve_n_queens_util(board, 0, n):
print("Solution does not exist")
return False
print(f"Solution for {n}-Queens:")
print_board(board)
return True
# --- Example Usage ---
if __name__ == "__main__":
try:
n = int(input("Enter the number of queens (N): "))
if n <= 0:
print("Please enter a positive integer.")
else:
solve_n_queens(n)
except ValueError:
print("Invalid input. Please enter an integer.")
How it works
solve_n_queens(n): This initializes an N×N board filled with . (representing empty spots) and starts the process at column 0.
solve_n_queens_util(board, col, n): This is the recursive engine.
- It tries to place a queen in the current
col.
- It loops through every
row in that column.
- It calls
is_safe() to ensure the spot isn't under attack.
- If safe, it places the
Q and recursively calls itself for the next column (col + 1).
- If the recursion returns
True, it means a solution was found downstream, so it returns True up the chain.
- If the recursion returns
False, it backtracks: it removes the queen (.) and tries the next row.
is_safe(board, row, col, n): Since we place queens one column at a time, from left to right, we only need to check for attacks coming from the left:
- The same row to the left.
- The upper-left diagonal.
- The lower-left diagonal.
- (We don't need to check the right side or the current column because we haven't placed anything there yet).