惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

Last Week in AI
Last Week in AI
阮一峰的网络日志
阮一峰的网络日志
P
Proofpoint News Feed
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
MongoDB | Blog
MongoDB | Blog
云风的 BLOG
云风的 BLOG
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
J
Java Code Geeks
WordPress大学
WordPress大学
T
The Blog of Author Tim Ferriss
V
Visual Studio Blog
小众软件
小众软件
Microsoft Azure Blog
Microsoft Azure Blog
博客园_首页
IT之家
IT之家
Vercel News
Vercel News
C
Check Point Blog
Google DeepMind News
Google DeepMind News
月光博客
月光博客
D
DataBreaches.Net
酷 壳 – CoolShell
酷 壳 – CoolShell
美团技术团队
Y
Y Combinator Blog
Hugging Face - Blog
Hugging Face - Blog

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant
How I Solved N-Queens Using Bitmasking (Step-by-Step Guide)
Abivarsan R · 2026-05-17 · via DEV Community
Cover image for How I Solved N-Queens Using Bitmasking (Step-by-Step Guide)

Abivarsan R

🚀 Solving N-Queens Using Bitmasking (Step-by-Step Guide)

🧠 Problem Overview

The N-Queens problem:

Place n queens on an n × n chessboard 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

Enter fullscreen mode Exit fullscreen mode

👉 All positions are free


🔹 Step 2: Find Available Positions

available = ~(cols | diag1 | diag2) & ((1 << n) - 1)

Enter fullscreen mode Exit fullscreen mode

Result:

available = 1111

Enter fullscreen mode Exit fullscreen mode

👉 All 4 columns are available


🔹 Step 3: Pick One Position

pos = available & -available

Enter fullscreen mode Exit fullscreen mode

👉 Picks rightmost 1

pos = 0001  → column 0

Enter fullscreen mode Exit fullscreen mode


🔹 Step 4: Place Queen

Board:

Q...
....
....
....

Enter fullscreen mode Exit fullscreen mode

Update masks:

cols  = 0001
diag1 = 0010   (shift left)
diag2 = 0000   (shift right)

Enter fullscreen mode Exit fullscreen mode


🔹 Step 5: Move to Next Row

Now row = 1

Find available:

available = ~(0001 | 0010 | 0000) = 1100

Enter fullscreen mode Exit fullscreen mode

👉 Only column 2 and 3 are free


🔹 Step 6: Repeat Process

Pick:

pos = 0100  → column 2

Enter fullscreen mode Exit fullscreen mode

Place queen:

Q...
..Q.
....
....

Enter fullscreen mode Exit fullscreen mode

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 🎉

Enter fullscreen mode Exit fullscreen mode

👉 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

Enter fullscreen mode Exit fullscreen mode


⚡ Key Tricks Explained

✔ Get all safe positions

available = ~(cols | diag1 | diag2) & ((1 << n) - 1)

Enter fullscreen mode Exit fullscreen mode


✔ Pick one position

pos = available & -available

Enter fullscreen mode Exit fullscreen mode


✔ Remove used position

available = available & (available - 1)

Enter fullscreen mode Exit fullscreen mode


⏱️ Complexity

Time: O(N!)
Space: O(N)

Enter fullscreen mode Exit fullscreen mode

👉 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 💡


🔖 Tags

Algorithms #Backtracking #Bitmasking #LeetCode #CodingInterview #DSA