π Solving N-Queens Using Bitmasking (Step-by-Step Guide)
π§ Problem Overview
The N-Queens problem:
Place
nqueens on ann Γ nchessboard such that no two queens attack each other.
β‘ Why Bitmasking?
Instead of using:
- Sets β
- Arrays β
We use:
- Bits (0/1) β β faster & efficient
π₯ Core Idea
We track:
-
colsβ occupied columns -
diag1β main diagonals (β) -
diag2β anti-diagonals (β)
Each is stored as a binary number
π§© Step-by-Step Explanation (VERY SIMPLE)
Letβs understand with n = 4
πΉ Step 1: Initial State
Row = 0
cols = 0000
diag1 = 0000
diag2 = 0000
π All positions are free
πΉ Step 2: Find Available Positions
available = ~(cols | diag1 | diag2) & ((1 << n) - 1)
Result:
available = 1111
π All 4 columns are available
πΉ Step 3: Pick One Position
pos = available & -available
π Picks rightmost 1
pos = 0001 β column 0
πΉ Step 4: Place Queen
Board:
Q...
....
....
....
Update masks:
cols = 0001
diag1 = 0010 (shift left)
diag2 = 0000 (shift right)
πΉ Step 5: Move to Next Row
Now row = 1
Find available:
available = ~(0001 | 0010 | 0000) = 1100
π Only column 2 and 3 are free
πΉ Step 6: Repeat Process
Pick:
pos = 0100 β column 2
Place queen:
Q...
..Q.
....
....
Update masks and continueβ¦
πΉ Step 7: Dead End? Backtrack!
If no positions available:
π Go back (remove previous queen)
π Try next possibility
πΉ Step 8: When Row == n
All queens placed successfully π
π Save board as a solution
π» Final Bitmask Code
class Solution(object):
def solveNQueens(self, n):
result = []
board = ["." * n for _ in range(n)]
def backtrack(row, cols, diag1, diag2):
if row == n:
result.append(board[:])
return
available = ~(cols | diag1 | diag2) & ((1 << n) - 1)
while available:
pos = available & -available
available = available & (available - 1)
col = (pos.bit_length() - 1)
board[row] = board[row][:col] + "Q" + board[row][col+1:]
backtrack(
row + 1,
cols | pos,
(diag1 | pos) << 1,
(diag2 | pos) >> 1
)
board[row] = board[row][:col] + "." + board[row][col+1:]
backtrack(0, 0, 0, 0)
return result
β‘ Key Tricks Explained
β Get all safe positions
available = ~(cols | diag1 | diag2) & ((1 << n) - 1)
β Pick one position
pos = available & -available
β Remove used position
available = available & (available - 1)
β±οΈ Complexity
Time: O(N!)
Space: O(N)
π But very fast in practice π
π§ Easy Memory Trick
π βUse bits to mark attacks, and pick positions using binary tricksβ
π‘ Interview Tip
Say this confidently:
βI optimized N-Queens using bitmasking to reduce constraint checking to constant time.β
π₯ Thatβs a standout answer
π Final Thought
Bitmasking turns a normal backtracking solution into a high-performance algorithm.
Once you understand this, you unlock a new level of problem-solving π‘
Top comments (0)