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:
Imagine placing game pieces on a grid where no two pieces can threaten each other horizontally, vertically, or diagonally. The brute force approach systematically tries placing the pieces on every possible square of the grid to test all potential arrangements.
Here's how the algorithm would work step-by-step:
class Solution:
def totalNQueens(self, board_size: int) -> int:
def backtrack_queens(row_index, columns, diagonals_main, diagonals_anti):
if row_index == board_size:
return 1
# We prune invalid branches early to avoid exploring useless configurations
valid_solutions_count = 0
for column_index in range(board_size):
main_diagonal_key = row_index - column_index
anti_diagonal_key = row_index + column_index
if column_index in columns or main_diagonal_key in diagonals_main or anti_diagonal_key in diagonals_anti:
continue
columns.add(column_index)
diagonals_main.add(main_diagonal_key)
diagonals_anti.add(anti_diagonal_key)
valid_solutions_count += backtrack_queens(row_index + 1, columns, diagonals_main, diagonals_anti)
columns.remove(column_index)
diagonals_main.remove(main_diagonal_key)
diagonals_anti.remove(anti_diagonal_key)
return valid_solutions_count
# We initialize the tracking sets to maintain state across recursive depth
active_columns = set()
active_main_diagonals = set()
active_anti_diagonals = set()
return backtrack_queens(0, active_columns, active_main_diagonals, active_anti_diagonals)Instead of checking every single possible square on the board, the optimal strategy builds the solution row by row. It uses a clever tracking system to instantly spot which diagonal paths and columns are blocked, avoiding dead ends before they happen.
Here's how the algorithm would work step-by-step:
class Solution:
def totalNQueens(self, board_size: int) -> int:
total_solutions_found = 0
columns_set = set()
positive_diagonals_set = set()
negative_diagonals_set = set()
def backtrack(current_row_index):
nonlocal total_solutions_found
# Reaching beyond the final row means a valid configuration was successfully completed.
if current_row_index == board_size:
total_solutions_found += 1
return
for current_column_index in range(board_size):
positive_diagonal_index = current_row_index + current_column_index
negative_diagonal_index = current_row_index - current_column_index
# Skip placements that violate existing diagonal or vertical constraints.
if (current_column_index in columns_set or
positive_diagonal_index in positive_diagonals_set or
negative_diagonal_index in negative_diagonals_set):
continue
columns_set.add(current_column_index)
positive_diagonals_set.add(positive_diagonal_index)
negative_diagonals_set.add(negative_diagonal_index)
backtrack(current_row_index + 1)
# Undo the placement to explore alternative configurations for previous rows.
columns_set.remove(current_column_index)
positive_diagonals_set.remove(positive_diagonal_index)
negative_diagonals_set.remove(negative_diagonal_index)
backtrack(0)
return total_solutions_found| Case | How to Handle |
|---|---|
| n equals 1 | The backtracking algorithm should immediately place the queen at row 0 column 0 and return 1. |
| n equals 2 or 3 | The algorithm explores all combinations and correctly yields 0 as no valid placements exist. |
| n equals 4 | The classic smallest non-trivial board size should correctly return 2 distinct solutions. |
| n equals 9, the upper constraint limit | An optimized backtracking solution using bit manipulation processes this within the time limit without TLE. |
| Zero or negative n values | Input validation should return 0 since a chessboard cannot have a non-positive dimension. |
| Large recursion depth leading to stack overflow | Since n is capped at 9 in standard constraints, the call stack depth remains safely within system limits. |
| Bitwise operations overflow in Java or C++ | Using standard integer or long types is sufficient since 9 bits easily fit within 32-bit and 64-bit integers. |
| Symmetric solutions being double counted | Row-by-row recursive placement naturally generates unique configurations by fixing one queen per row. |