The n-queens puzzle is the problem of placing n queens on an n x n chessboard such that no two queens attack each other.
Given an integer n, return the number of distinct solutions to the n-queens puzzle.
Example 1:
Input: n = 4 Output: 2 Explanation: There are two distinct solutions to the 4-queens puzzle as shown.
Example 2:
Input: n = 1 Output: 1
Constraints:
1 <= n <= 9When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:
The brute force approach tries every single possible arrangement of queens on the board. We systematically explore each configuration, and if a configuration is valid (no queens attack each other), we count it. This approach guarantees finding all solutions, but it's very inefficient.
Here's how the algorithm would work step-by-step:
def total_n_queens(n):
number_of_solutions = 0
queens_positions = []
def is_safe(row_index, column_index):
for previous_row_index, previous_column_index in enumerate(queens_positions):
if column_index == previous_column_index or \
abs(column_index - previous_column_index) == abs(row_index - previous_row_index):
return False
return True
def solve_n_queens_recursive(row_index):
nonlocal number_of_solutions
# Base case: all queens are placed
if row_index == n:
number_of_solutions += 1
return
for column_index in range(n):
# Check if this position is safe
if is_safe(row_index, column_index):
# Place the queen
queens_positions.append(column_index)
# Recursively solve for the next row
solve_n_queens_recursive(row_index + 1)
# Backtrack: remove the queen
queens_positions.pop()
# Initiate the recursive process
solve_n_queens_recursive(0)
return number_of_solutionsWe want to find the number of ways to place queens on a board so they don't attack each other. The efficient way is to explore possible queen placements one row at a time and stop exploring a path as soon as we find an attack.
Here's how the algorithm would work step-by-step:
def total_n_queens(number_of_queens):
solution_count = 0
def is_safe(row_position, column_position, queen_positions):
for row_index in range(row_position):
column_index = queen_positions[row_index]
if column_index == column_position or \
abs(column_index - column_position) == row_position - row_index:
return False
return True
def solve_n_queens(row_position, queen_positions):
nonlocal solution_count
if row_position == number_of_queens:
solution_count += 1
return
# Iterate through columns in current row
for column_position in range(number_of_queens):
# Check if queen can be placed here
if is_safe(row_position, column_position, queen_positions):
queen_positions[row_position] = column_position
# Move to the next row to place a queen
solve_n_queens(row_position + 1, queen_positions)
# Initialize array to track queen positions
queen_positions = [0] * number_of_queens
# Start placing queens from the first row
solve_n_queens(0, queen_positions)
return solution_count| Case | How to Handle |
|---|---|
| n = 0 (Empty board) | Return 1, as there is one way to place zero queens (do nothing). |
| n = 1 (Single cell board) | Return 1, as a single queen can be placed on the cell. |
| n = 2 or n = 3 (No solutions) | Return 0, as no valid arrangement of queens exists for these board sizes. |
| Large n (e.g., n = 12+) | Ensure the algorithm scales reasonably well, using techniques like bit manipulation for representation to improve performance or memoization of smaller subproblems to reduce computations. |
| Integer overflow when calculating solution count for large n (language-specific) | Use a data type that can accommodate the number of solutions (e.g., long in Java/C++, or arbitrary precision integers if necessary). |
| Deep recursion calls with large n causing stack overflow. | If recursion depth becomes an issue, switch to an iterative approach using a stack to simulate the recursive calls, or implement memoization if possible. |
| Negative input for n | Throw an IllegalArgumentException or return 0 (invalid input). |
| n is a non-integer value | Type checking or conversion to integer with appropriate error handling if necessary. |