Print all possible solutions to the N-Queens problem.
HardPlace n queens on an n x n chessboard so that no two queens attack each other. A queen attacks every square in its row, its column and both of its diagonals.
Return every distinct arrangement. Write each board as a list of n strings, one per row, where "Q" marks a queen and "." marks an empty square. The boards can be in any order.
Example 1
Input: n = 4 Output: [[".Q..", "...Q", "Q...", "..Q."], ["..Q.", "Q...", "...Q", ".Q.."]]
A 4 x 4 board has exactly two arrangements, and each is the mirror image of the other.
Example 2
Input: n = 3 Output: []
No arrangement works on a 3 x 3 board.
Constraints
1 <= n <= 9
Approach
Trying every set of n squares is hopeless even for small boards. Two observations shrink the search. Every row needs exactly one queen, so you only choose a column for each row. And as soon as a partial board has two queens attacking each other, no way of filling the remaining rows can fix it, so that branch can be abandoned immediately.
Place queens from the top row down. For each column in the current row, check whether it's attacked by a queen already placed. Three sets make the check O(1): used columns, used diagonals (row - col is constant along each one) and used anti-diagonals (row + col is constant along each one). If the square is safe, record it, recurse into the next row, then remove it from the sets before trying the next column. Reaching row n means every row has a queen, so build the board strings and save them.
Steps
- Keep an array of the queen's column in each row and three sets for used columns, diagonals and anti-diagonals.
- In
place(row), ifrow == n, convert the columns into board strings and save them. - Otherwise, for each column, skip it if its column, diagonal or anti-diagonal is in use.
- Mark the square, call
place(row + 1), then unmark it. - Start with
place(0)and return every saved board.
Complexity
- Time:
O(n!). The first row hasnchoices, the next at mostn - 1and so on, and building each board addsO(n^2). - Space:
O(n)for the recursion and the sets, not counting the output.
Common mistakes
- Checking only columns and forgetting one of the two diagonal directions.
- Forgetting to remove a queen from the sets after the recursive call returns, which blocks squares that should be free.
- Saving a reference to a board that keeps changing instead of building a fresh copy for each solution.
Related courses



