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.
Input: n = 4
Output: [[".Q..","...Q","Q...","..Q."],["..Q.","Q...","...Q",".Q.."]]
Input: n = 1
Output: [["Q"]]
Constraint: No two queens in same row, column, or diagonal.
Strategy: Place one queen per row, checking if position is safe.
For each row:
This is a Constraint Satisfaction backtracking problem:
def backtrack(row):
if row == n:
result.append(build_board())
return
for col in range(n):
if is_safe(row, col):
place_queen(row, col)
backtrack(row + 1)
remove_queen(row, col)
def is_safe(row, col):
# Check column
# Check diagonal (top-left to bottom-right)
# Check anti-diagonal (top-right to bottom-left)
Optimization: Use sets to track columns and diagonals in O(1).
Time: O(n!)
Space: O(n²) for board
1import java.util.*;
2
3class Solution {
4 public List<List<String>> solveNQueens(int n) {
5 List<List<String>> result = new ArrayList<>();
6 char[][] board = new char[n][n];
7
8 for (int i = 0; i < n; i++) {
9 Arrays.fill(board[i], '.');
10 }
11
12 Set<Integer> cols = new HashSet<>();
13 Set<Integer> diags = new HashSet<>();
14 Set<Integer> antiDiags = new HashSet<>();
15
16 backtrack(0, n, board, cols, diags, antiDiags, result);
17 return result;
18 }
19
20 private void backtrack(int row, int n, char[][] board,
21 Set<Integer> cols, Set<Integer> diags,
22 Set<Integer> antiDiags, List<List<String>> result) {
23 if (row == n) {
24 result.add(buildBoard(board));
25 return;
26 }
27
28 for (int col = 0; col < n; col++) {
29 if (cols.contains(col) ||
30 diags.contains(row - col) ||
31 antiDiags.contains(row + col)) {
32 continue;
33 }
34
35 // Place queen
36 board[row][col] = 'Q';
37 cols.add(col);
38 diags.add(row - col);
39 antiDiags.add(row + col);
40
41 backtrack(row + 1, n, board, cols, diags, antiDiags, result);
42
43 // Remove queen (backtrack)
44 board[row][col] = '.';
45 cols.remove(col);
46 diags.remove(row - col);
47 antiDiags.remove(row + col);
48 }
49 }
50
51 private List<String> buildBoard(char[][] board) {
52 List<String> result = new ArrayList<>();
53 for (char[] row : board) {
54 result.add(new String(row));
55 }
56 return result;
57 }
58}
59