Providing bitwise vs standard N-Queens code
Here's Python code solving N-Queens with both standard 2D backtracking and an optimized bitwise approach using three integers for columns and diagonals, plus timing to illustrate typical speed differences for N=14.
Below is a concise Python example comparing a straightforward backtracking approach (using row-by-row checks) to a bitwise solution that tracks columns and diagonals in three integers. For large N (like N=14), the bitwise version can be many times faster. The bitwise method works by keeping bitmasks that mark which columns and diagonals are already “attacked” by previously placed queens.
import time
def n_queens_backtracking(n):
solutions = 0
cols = set()
diag1 = set() # r + c
diag2 = set() # r - c
def backtrack(r):
nonlocal solutions
if r == n:
solutions += 1
return
for c in range(n):
if c in cols or (r + c) in diag1 or (r - c) in diag2:
continue
cols.add(c)
diag1.add(r + c)
diag2.add(r - c)
backtrack(r + 1)
cols.remove(c)
diag1.remove(r + c)
diag2.remove(r - c)
backtrack(0)
return solutions
def n_queens_bitmask(n):
"""Bitwise solution that returns the number of solutions."""
solutions = 0
full_mask = (1 << n) - 1 # Bits set for all valid columns
def solve(row, cols, left_diags, right_diags):
nonlocal solutions
if row == n:
solutions += 1
return
# Compute all safe positions (1 bits) for this row
available = full_mask & ~(cols | left_diags | right_diags)
while available:
# Pick the rightmost 1-bit (LSB)
bit = available & -available
available -= bit
# Place queen; update masks
solve(row + 1,
cols | bit,
(left_diags | bit) << 1,
(right_diags | bit) >> 1)
solve(0, 0, 0, 0)
return solutions
if __name__ == "__main__":
N = 14
# Standard backtracking
start = time.perf_counter()
ans_backtracking = n_queens_backtracking(N)
t_backtracking = time.perf_counter() - start
# Bitwise solution
start = time.perf_counter()
ans_bitmask = n_queens_bitmask(N)
t_bitmask = time.perf_counter() - start
print(f"N = {N}")
print(f"Standard Backtracking: {ans_backtracking} solutions in {t_backtracking:.4f} seconds")
print(f"Bitwise Solution : {ans_bitmask} solutions in {t_bitmask:.4f} seconds")
How it works (bitwise part):
- We keep three bitmasks:
cols tracks which columns are already occupied.
left_diags tracks “left” diagonals () being attacked.
right_diags tracks “right” diagonals (/) being attacked.
- On each row, we compute
available = all columns not under attack.
- We select one valid spot at a time (
bit = available & -available), update masks, and recurse to the next row.
Typical result for N=14 is 365596 solutions. The bitwise approach generally runs many times faster than the naive backtracking—on a typical machine, it can complete in well under a second for N=14, whereas plain backtracking may take significantly longer.