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 all distinct solutions to the n-queens puzzle. You may return the answer in any order.
Each solution contains a distinct board configuration of the n-queens' placement, where 'Q' and '.' both indicate a queen and an empty space, respectively.
Example 1:
Input: n = 4 Output: [[".Q..","...Q","Q...","..Q."],["..Q.","Q...","...Q",".Q.."]] Explanation: There exist two distinct solutions to the 4-queens puzzle as shown above
Example 2:
Input: n = 1 Output: [["Q"]]
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 you need to place a specific number of queens on a game board of the same size so that no queen can attack any other. The brute force approach involves testing every single possible way to place the queens on the board and checking each layout to see if it is safe.
Here's how the algorithm would work step-by-step:
class Solution:
def solveNQueens(self, board_size: int):
all_solutions = []
current_board = [-1] * board_size
def is_layout_safe(queen_positions):
row_index = len(queen_positions) - 1
for previous_row in range(row_index):
column_difference = abs(queen_positions[previous_row] - queen_positions[row_index])
row_difference = row_index - previous_row
if column_difference == 0 or column_difference == row_difference:
return False
return True
def explore_combinations(current_row):
if current_row == board_size:
formatted_solution = []
for queen_column in current_board:
formatted_solution.append("." * queen_column + "Q" + "." * (board_size - 1 - queen_column))
all_solutions.append(formatted_solution)
return
# We must test every column position in the current row to find all possible placements
for column_index in range(board_size):
current_board[current_row] = column_index
# We check the layout safety early to prune invalid subtrees and avoid wasted work
if is_layout_safe(current_board[:current_row + 1]):
explore_combinations(current_row + 1)
current_board[current_row] = -1
explore_combinations(0)
return all_solutionsInstead of blindly testing every possible position for every game piece on the entire board, we place pieces row by row and immediately abandon any path the moment a piece threatens another. This smart shortcut prevents us from wasting time exploring dead ends that violate the safety rules.
Here's how the algorithm would work step-by-step:
class Solution:
def solveNQueens(self, board_dimension: int) -> list[list[str]]:
all_valid_solutions = []
occupied_columns = set()
positive_diagonals = set()
negative_diagonals = set()
current_board_state = []
def backtrack_rows(current_row):
if current_row == board_dimension:
formatted_board = []
for row_index in current_board_state:
formatted_board.append("." * row_index + "Q" + "." * (board_dimension - row_index - 1))
all_valid_solutions.append(formatted_board)
return
for column_index in range(board_dimension):
# We prune branches instantly when a queen threatens another via columns or diagonals.
if (column_index in occupied_columns or
(current_row - column_index) in positive_diagonals or
(current_row + column_index) in negative_diagonals):
continue
occupied_columns.add(column_index)
positive_diagonals.add(current_row - column_index)
negative_diagonals.add(current_row + column_index)
current_board_state.append(column_index)
backtrack_rows(current_row + 1)
# Backtracking allows us to undo our previous placement and explore alternative safe spots.
current_board_state.pop()
negative_diagonals.remove(current_row + column_index)
positive_diagonals.remove(current_row - column_index)
occupied_columns.remove(column_index)
backtrack_rows(0)
return all_valid_solutions| Case | How to Handle |
|---|---|
| Input n equals 1 | The backtracking algorithm immediately places the single queen at position zero and returns the single valid board configuration. |
| Input n equals 2 or 3 | The recursive exploration will exhaust all possibilities and correctly return an empty list because no valid non-attacking configuration exists for these sizes. |
| Maximum standard constraint where n equals 9 | The backtracking approach scales efficiently within time limits by pruning invalid branches early via diagonal and column tracking sets. |
| Zero or negative values for n | The problem constraints typically define n as a positive integer at least 1, but input validation should immediately return an empty list. |
| Deep recursion stack for larger n values up to 9 | The maximum recursion depth is bounded by n, which safely avoids stack overflow errors in standard runtime environments. |
| Multiple valid solutions exist for larger n such as n equals 8 | The algorithm uses a global or passed accumulator list to collect every distinct valid board configuration during the backtracking traversal. |
| Symmetric solutions generated during board traversal | The standard backtracking algorithm treats mirrored or rotated configurations as distinct solutions as required by the problem statement. |
| Memory limits due to large output size for larger boards | String formatting is performed only upon finding a complete valid configuration to minimize intermediate memory overhead. |