Problem
Section titled “Problem”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 = 4Output: [[".Q..","...Q","Q...","..Q."],["..Q.","Q...","...Q",".Q.."]]Explanation: There exist two distinct solutions to the 4-queens puzzle as shown aboveExample 2:
Input: n = 1Output: [["Q"]]Constraints:
Solution approach
Section titled “Solution approach”Intuition
Section titled “Intuition”Two queens in the same row attack each other, so a solution has exactly one queen per row. That turns the search into: for row 0, then row 1, and so on, choose a column for that row’s queen. This is a natural fit for backtracking — place a queen, recurse to the next row, and remove it again to try the next column.
A placement at (row, col) is legal only if no earlier queen shares its column or one of its two diagonals. Diagonals have a simple signature:
- on a down-right diagonal (
\),row - colis constant — shift it torow - col + n - 1to get an index in[0, 2n - 2]; - on a down-left diagonal (
/),row + colis constant, already in[0, 2n - 2].
So three boolean arrays — cols, diag and anti — tell in whether a square is attacked, instead of scanning the board. Marking them on placement and clearing them on removal keeps them in sync with the current partial board. Branches die as soon as a row has no safe column, which prunes the search far below the raw possibilities.
Algorithm
Section titled “Algorithm”- Start with
boardasnstrings of'.', andcols(sizen),diagandanti(size2n - 1) allfalse. place(row):- if
row == n, every row has a queen: append a copy ofboardtoansand return; - for each
colin0 .. n - 1, skip it ifcols[col],diag[row - col + n - 1]oranti[row + col]is set; otherwise set all three, put'Q'atboard[row][col], callplace(row + 1), then clear the three flags and restore'.'.
- if
- Call
place(0)and returnans.
Walkthrough
Section titled “Walkthrough”Backtracking on n = 4 until the first solution. Blue is the queen just placed, purple the queens already on the board, red the squares in later rows that they attack; a row that is entirely red forces a backtrack:
Complexity
Section titled “Complexity”- Time: — row
0has at mostnchoices, row1at mostn - 1safe columns, and so on, so the search tree has nodes, each scanning itsncolumns with checks (in practice pruning keeps it far smaller); copying each of theSsolutions costs an extra . - Space: — the working
board; the flag arrays and the recursion stack are (not counting the output).
Edge cases
Section titled “Edge cases”n = 1: the only square is safe, giving[["Q"]].n = 2andn = 3: no solution exists; every branch dies and an empty list is returned.
Think before you peek
Work out an approach on your own first — the explanation will still be here when you want it.
class Solution { int n; vector<string> board; vector<bool> cols, diag, anti; // diag: row - col + n - 1, anti: row + col vector<vector<string>> ans;
void place(int row) { if (row == n) { ans.push_back(board); return; } for (int col = 0; col < n; col++) { int d = row - col + n - 1, a = row + col; if (cols[col] || diag[d] || anti[a]) continue; cols[col] = diag[d] = anti[a] = true; board[row][col] = 'Q'; place(row + 1); board[row][col] = '.'; cols[col] = diag[d] = anti[a] = false; } }
public: vector<vector<string>> solveNQueens(int n) { this->n = n; board.assign(n, string(n, '.')); cols.assign(n, false); diag.assign(2 * n - 1, false); anti.assign(2 * n - 1, false); place(0); return ans; }};class Solution { private int n; private char[][] board; private boolean[] cols, diag, anti; // diag: row - col + n - 1, anti: row + col private List<List<String>> ans;
private void place(int row) { if (row == n) { List<String> solution = new ArrayList<>(n); for (char[] r : board) solution.add(new String(r)); ans.add(solution); return; } for (int col = 0; col < n; col++) { int d = row - col + n - 1, a = row + col; if (cols[col] || diag[d] || anti[a]) continue; cols[col] = diag[d] = anti[a] = true; board[row][col] = 'Q'; place(row + 1); board[row][col] = '.'; cols[col] = diag[d] = anti[a] = false; } }
public List<List<String>> solveNQueens(int n) { this.n = n; board = new char[n][n]; for (char[] r : board) Arrays.fill(r, '.'); cols = new boolean[n]; diag = new boolean[2 * n - 1]; anti = new boolean[2 * n - 1]; ans = new ArrayList<>(); place(0); return ans; }}class Solution: def solveNQueens(self, n: int) -> list[list[str]]: board = [["."] * n for _ in range(n)] cols = [False] * n diag = [False] * (2 * n - 1) # row - col + n - 1 anti = [False] * (2 * n - 1) # row + col ans = []
def place(row): if row == n: ans.append(["".join(r) for r in board]) return for col in range(n): d, a = row - col + n - 1, row + col if cols[col] or diag[d] or anti[a]: continue cols[col] = diag[d] = anti[a] = True board[row][col] = "Q" place(row + 1) board[row][col] = "." cols[col] = diag[d] = anti[a] = False
place(0) return ansGive it a try first
Attempt the problem on LeetCode — the code will still be here.













