N-Queens - Problem
The n-queens puzzle is a classic problem of placing n queens on an n × n chessboard such that no two queens can attack each other.
In chess, a queen can attack any piece that lies in the same row, column, or diagonal as the queen.
Given an integer n, return all distinct solutions to the n-queens puzzle. Each solution should represent the board configuration where 'Q' indicates a queen and '.' indicates an empty space.
Input & Output
Example 1 — Classic 4-Queens
$
Input:
n = 4
›
Output:
[[".Q..","...Q","Q...","..Q."],["..Q.","Q...","...Q",".Q.."]]
💡 Note:
For a 4×4 board, there are exactly 2 distinct solutions. First solution places queens at (0,1), (1,3), (2,0), (3,2). Second solution places queens at (0,2), (1,0), (2,3), (3,1). Both arrangements ensure no two queens can attack each other.
Example 2 — Simple 1-Queen
$
Input:
n = 1
›
Output:
[["Q"]]
💡 Note:
For a 1×1 board, there's only one position and one queen, so the single solution is just placing the queen at (0,0).
Example 3 — Impossible Case
$
Input:
n = 2
›
Output:
[]
💡 Note:
For a 2×2 board, it's impossible to place 2 queens without them attacking each other. Any placement will result in queens being on the same row, column, or diagonal.
Constraints
- 1 ≤ n ≤ 9
Visualization
Tap to expand
Understanding the Visualization
1
Input
Integer n representing board size and number of queens
2
Constraint
No two queens can attack each other (same row, column, or diagonal)
3
Output
All possible board configurations as string arrays
Key Takeaway
🎯 Key Insight: Use backtracking with constraint checking to efficiently explore only valid paths
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code