N-Queens II - Problem
The N-Queens puzzle is a classic backtracking problem where you need to place n chess queens on an n × n chessboard such that no two queens can attack each other.
Two queens attack each other if they are:
- On the same row
- On the same column
- On the same diagonal (both main diagonal and anti-diagonal)
Given an integer n, return the number of distinct solutions to the N-Queens puzzle.
Input & Output
Example 1 — Small Board
$
Input:
n = 4
›
Output:
2
💡 Note:
There are exactly 2 distinct solutions for a 4×4 board. Solution 1: queens at positions (0,1), (1,3), (2,0), (3,2). Solution 2: queens at positions (0,2), (1,0), (2,3), (3,1).
Example 2 — Minimal Board
$
Input:
n = 1
›
Output:
1
💡 Note:
For n=1, there's only one cell on the board, so exactly 1 solution: place the single queen at position (0,0).
Example 3 — Impossible Case
$
Input:
n = 2
›
Output:
0
💡 Note:
On a 2×2 board, it's impossible to place 2 queens without them attacking each other. Any placement results in queens sharing a row, column, or diagonal.
Constraints
- 1 ≤ n ≤ 9
Visualization
Tap to expand
Understanding the Visualization
1
Input
Board size n=4
2
Process
Find all valid queen placements
3
Output
Count of distinct solutions: 2
Key Takeaway
🎯 Key Insight: Use backtracking with sets to efficiently count all valid N-Queens arrangements
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code