N-Queens

Hard
backtracking

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.

Queens can attack horizontally, vertically, and diagonally. Therefore, no two queens can share:

  • The same row
  • The same column
  • The same diagonal (either direction)

The backtracking approach: place queens row by row. For each row, try each column and check if the placement is safe (no conflicts with already-placed queens). If safe, recurse to next row. If all rows filled, we found a solution.

Example 1

Input: n = 4
Output: [[".Q..","...Q","Q...","..Q."],["..Q.","Q...","...Q",".Q.."]]
Explanation: There are two ways to place 4 queens on a 4x4 board without any attacks.

Example 2

Input: n = 1
Output: [["Q"]]
Explanation: Single queen on 1x1 board - trivially valid.

Constraints

  • 1 <= n <= 9
Show Hints (4)
Hint 1: Place queens one row at a time. This automatically handles row conflicts.
Hint 2: For column conflicts, track which columns are already occupied.
Hint 3: For diagonal conflicts, notice that cells on the same diagonal have: row-col = constant (one direction) or row+col = constant (other direction).
Hint 4: Use sets to track occupied columns and diagonals for O(1) lookup.
Loading editor...

Test Results

Click "Run" to execute your code against test cases

AI Tutor

Socratic guidance - I'll ask questions, not give answers

AI Tutor
Hello! I'm your AI tutor, here to guide you through this problem using the Socratic method. I won't give you direct answers, but I'll ask questions and provide hints to help you discover the solution yourself. What's your first instinct when you look at this problem? What approach comes to mind?