N-Queens II - Problem
The N-Queens II problem is a classic backtracking puzzle that challenges you to count the number of ways to place n chess queens on an n ร n chessboard.
The Challenge: Queens are powerful pieces that can attack any piece in the same row, column, or diagonal. Your task is to find how many distinct arrangements exist where no two queens can attack each other.
Input: An integer n representing the size of the chessboard and the number of queens to place.
Output: The total count of valid arrangements (solutions).
Example: For n = 4, there are exactly 2 distinct solutions where 4 queens can be placed on a 4ร4 board without attacking each other.
Input & Output
example_1.py โ Basic Case
$
Input:
n = 4
โบ
Output:
2
๐ก Note:
For a 4ร4 board, there are exactly 2 ways to place 4 queens such that none attack each other. The two solutions have queens at positions [(0,1),(1,3),(2,0),(3,2)] and [(0,2),(1,0),(2,3),(3,1)].
example_2.py โ Small Case
$
Input:
n = 1
โบ
Output:
1
๐ก Note:
On a 1ร1 board, there's only one way to place 1 queen - at position (0,0).
example_3.py โ 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, since any two positions will share a row, column, or diagonal.
Constraints
- 1 โค n โค 9
- The problem guarantees that n will be small enough to compute in reasonable time
- Note: For n โฅ 10, the computation time becomes prohibitively long even with optimal algorithms
Visualization
Tap to expand
Understanding the Visualization
1
Initialize
Start with empty board and conflict tracking sets
2
Place Queen
Try placing a queen in the first available position of current row
3
Update Conflicts
Add the queen's attack lines to conflict sets
4
Recurse or Backtrack
If valid, move to next row. If no valid positions remain, backtrack
5
Count Solution
When all n queens are placed successfully, increment solution count
Key Takeaway
๐ฏ Key Insight: Using conflict detection sets transforms an O(n) validity check into O(1), making backtracking dramatically more efficient by pruning invalid branches immediately.
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code