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
โ™•โ™•โ™•โ™•Backtracking Process:1. Place queen in row 0, col 12. Update conflict sets: โ€ข Columns: {1} โ€ข Diag1: {-1} โ€ข Diag2: {1}3. Try row 1: col 3 is safe4. Continue until solution foundโœ“ Solution count: 15. Backtrack to find more...Key Insight:Conflict sets enable O(1) validity checkinginstead of O(n) diagonal scanning, makingbacktracking much more efficient!
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.
Asked in
Google 45 Amazon 38 Microsoft 32 Meta 28
87.5K Views
Medium Frequency
~25 min Avg. Time
2.9K Likes
Ln 1, Col 1
Smart Actions
๐Ÿ’ก Explanation
AI Ready
๐Ÿ’ก Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen