Back
Queen icon
Article19 min read2025-12-10

Solving the N Queens Problem A Guide to Backtracking

Solving the N Queens Problem A Guide to Backtracking

The N‑Queens problem is a classic brain-teaser that sounds simple on the surface but quickly reveals its hidden depth. The challenge? Place N chess queens on an N×N chessboard so that no two queens threaten each other. This means no two queens can share the same row, column, or diagonal.

Unpacking the N Queens Puzzle

A chess board displays white and black pieces during a game, with green highlights indicating moves.

At its heart, the N‑Queens problem is way more than a chess challenge; it’s a brilliant exercise in computational thinking and algorithm design. Think of it like a tricky scheduling task. Imagine you have to book N meetings, each needing its own room and a unique time slot, but with a complex web of rules preventing certain meetings from overlapping.

Solving this puzzle requires a real strategy. Just guessing where to put the queens becomes hopeless as the board gets bigger. Each queen you place on the board instantly restricts the safe squares for all the others. This cascading effect is exactly what makes the problem so compelling.

The Core Rules of Engagement

To find a valid solution, every single queen has to obey three non-negotiable rules. Getting these rules straight is the first real step toward cracking the puzzle.

Here's a quick breakdown of the core constraints that define a correct N-Queens solution.

The Three Rules of Queen Placement

| Constraint | What It Means | Why It Is Crucial | | --- | --- | --- | | One Queen Per Row | Each horizontal row can only hold one queen. | This is the most straightforward rule to follow and helps simplify the search space. | | One Queen Per Column | Every vertical column is limited to a single queen. | Just like the row rule, this prevents obvious attacks and structures the problem. | | One Queen Per Diagonal | No two queens can share any diagonal path. | This is the trickiest constraint and where most manual attempts fail. It forces complex, non-linear thinking. |

These rules turn what could be a random guessing game into a systematic search for a solution. While many players start with fun chess puzzles for beginners, the N‑Queens problem pushes you to focus purely on logical placement, not on outsmarting an opponent.

The goal isn't to win a game but to find a state of perfect harmony on the board, where every piece coexists peacefully under a strict set of rules. This makes it a perfect gateway into the world of constraint satisfaction problems.

From Classic Puzzle to Modern Coder Challenge

The most famous version is the 8‑queens puzzle, played on a standard 8×8 board. Figuring out how many solutions existed was a major mathematical headache until the answer was finally confirmed in 1874. Today, we know there are exactly 92 distinct solutions.

Because of its clear rules and escalating difficulty, the 8‑queens problem has become a staple in UK computer science courses. In fact, over 85% of undergraduate programmes use it to teach core concepts like recursion and backtracking. You can dive deeper into its role in education by exploring academic resources like this workbook from Warwick University.

Why the N Queens Problem Is So Challenging

On the surface, the N Queens problem seems pretty simple. You have a board and a few pieces with straightforward rules. But once you actually try to solve it by just placing queens here and there, you quickly run into its true nature—this isn't just a logic puzzle; it's a serious combinatorial problem.

The real difficulty lies in what mathematicians call a combinatorial explosion. For a tiny 4x4 board, there are 1,820 ways to place four queens without them sharing a row or column. Checking the diagonals from there is a bit of a pain, but doable. But jump up to a standard 8x8 board, and that number skyrockets to 40,320 possible placements. The complexity doesn't just add up; it multiplies.

This insane growth rate means that a brute-force approach—trying every single arrangement—is completely useless for anything but the smallest boards. Each queen you place creates a new web of restrictions, and the number of dead ends just grows exponentially. This is exactly why we need clever algorithms, not just more powerful computers.

The Mystery of the Solution Count

One of the most fascinating parts of the N Queens problem is that there’s no clean formula to calculate the number of solutions for a board of size N. For centuries, mathematicians have tried and failed to come up with a neat equation like f(N) = ... that just works every time.

Instead, the number of solutions grows in a chaotic, unpredictable way. For example:

  • An 8x8 board has 92 solutions.
  • A 12x12 board has 14,200 solutions.
  • A 20x20 board has a mind-boggling 39,029,188,884 solutions.

This irregular pattern is what makes the problem so complex. Finding all the solutions requires a methodical, exhaustive search, and without a predictable pattern, you can’t take any shortcuts. This is a common theme in tough logic-based challenges, where you have to uncover the solution path step-by-step rather than just calculating it. If you want to sharpen that skill, our guide on how to solve logic puzzles is a great place to start.

From Puzzle to Advanced Mathematics

The puzzle's sheer difficulty has made it a topic of serious academic study. For a long time, researchers could only guess at the number of solutions for very large boards. But a huge breakthrough came in 2021 when mathematician Michael Simkin developed an asymptotic formula.

His work showed that for a large board of size N, the number of solutions is approximately (0.143 * N)^N. This formula finally gives us a remarkably close estimate of just how fast the solution count scales up.

This achievement really highlights the puzzle's journey from a 19th-century pastime to a topic studied in UK postgraduate courses at universities like Oxford and Warwick. It's a perfect example of modern mathematical techniques taking on a classic problem. This evolution is precisely why N Queens remains such a compelling challenge for beginners and experts alike.

Solving N Queens Using Backtracking

So, how do you actually solve the N-Queens problem? Trying to guess and check is a recipe for disaster. We need a system—a smart, methodical way to explore the possibilities without getting lost. The most common and intuitive approach is an algorithm called backtracking.

Think of it like navigating a giant maze. You walk down a path, and every time you hit a fork in the road, you make a choice. If you hit a dead end, you don't just give up. You retrace your steps—you "backtrack"—to the last fork and try the other path. That's exactly what our algorithm does.

It explores a path of choices by placing queens one by one. If a choice leads to an impossible situation (like two queens attacking each other), it undoes that move and tries the next best option.

The Core Logic of a Backtracking Solver

The backtracking process for N-Queens breaks down into a simple, recursive loop. We work our way across the board, column by column, trying to place a queen in each one.

Here’s the basic flow:

  1. Start at the first column (column 0).
  2. Try placing a queen in the first available row.
  3. Check if this spot is "safe." Is it attacked by any other queens already on the board? We only need to check the row and diagonals to the left, since we're placing one queen per column.
  4. If it's safe, lock in the queen and recursively move to the next column.
  5. If it's not safe, move the queen down to the next row in the same column and check again.
  6. If you run out of rows in a column, you've hit a dead end. This means a previous placement was a mistake. The algorithm then "backtracks" to the previous column, picks up that queen, and moves it to its next available row.
  7. Once a queen is safely placed in the final column, congratulations—you've found a solution! The algorithm can then backtrack again to keep searching for all other possible solutions.

This approach is brilliant because it systematically explores the entire "decision tree" of queen placements while smartly pruning any branch that can't possibly lead to a solution. It's much faster than a brute-force attack, which would mindlessly check every single combination.

The challenge grows exponentially, which is why an efficient search method like backtracking is so crucial.

Diagram showing three progressively larger square boards: a 4x4, an 8x8, and a general N x N board.

As the board gets bigger, the search space explodes. A naive approach quickly becomes impossible to compute.

A Practical Example in Python

Seeing the code makes it all click. Here's a clean, simple Python example that puts the backtracking logic into action. It has a function to check for safety and a core recursive function that drives the solver.

def is_safe(board, row, col, N): # Check this row on the left side for i in range(col): if board[row][i] == 1: return False

# Check upper diagonal on the left side
for i, j in zip(range(row, -1, -1), range(col, -1, -1)):
    if board[i][j] == 1:
        return False

# Check lower diagonal on the left side
for i, j in zip(range(row, N, 1), range(col, -1, -1)):
    if board[i][j] == 1:
        return False

return True

def solve_n_queens_util(board, col, N): # Base case: If all queens are placed, we found a solution if col >= N: return True

# Consider this column and try placing a queen in all rows
for i in range(N):
    if is_safe(board, i, col, N):
        # Place the queen
        board[i][col] = 1

        # Recur to place the rest of the queens
        if solve_n_queens_util(board, col + 1, N):
            return True

        # If placing queen in board[i][col] doesn't lead to a solution,
        # then remove the queen (backtrack)
        board[i][col] = 0

# If the queen cannot be placed in any row in this column, return false
return False

The essence of backtracking is this: Make a choice. Explore the consequences. If it doesn't work out, undo the choice and try something else. It's a powerful problem-solving pattern that mirrors how we often approach complex decisions in real life.

By translating this trial-and-error logic into a structured algorithm, we can conquer the N-Queens problem on boards far larger than we could ever hope to solve by hand. While this basic implementation works perfectly, it can be made much faster with some clever optimisations, which we’ll explore next.

How to Optimise Your N Queens Solver

The basic backtracking algorithm gets the job done, but you'll quickly notice it starts to chug as the board gets bigger. For a large N, the sheer number of possibilities can bring even a smart algorithm to its knees.

The good news? We can make our solver dramatically faster by rethinking how it checks for threats.

The bottleneck in our first attempt is the is_safe() function. Every single time we consider placing a queen, the function scans the board all over again, checking rows and diagonals for threats. This constant re-scanning is a huge waste of time. Why recalculate what you already know? A much smarter approach is to simply remember which rows and diagonals are already under attack.

Using Arrays for Instant Lookups

Instead of re-scanning the board, we can use simple arrays to keep track of attacked positions. This gives us what’s called a constant-time lookup, written as O(1). It means the check is practically instant, no matter how big the board gets. It's like having a cheat sheet instead of re-reading a whole book every time you need one fact.

To make this work, we need to track three things:

  • Attacked Columns: A simple boolean array cols[N], where cols[i] is true if a queen is in that column.
  • Attacked Main Diagonals: A boolean array main_diag[2*N - 1] tracks the diagonals running from top-left to bottom-right. Any cell (row, col) on the same main diagonal shares the same value for row - col.
  • Attacked Anti-Diagonals: Similarly, anti_diag[2*N - 1] handles diagonals from top-right to bottom-left. Cells here share the same value for row + col.

With these lookup arrays in place, our is_safe() check becomes a lightning-fast query: if not cols[c] and not main_diag[r-c] and not anti_diag[r+c]. This one change delivers a massive performance boost, especially for a large N Queens problem.

This shift from repeated calculation to instant lookup is a fundamental trick in algorithm design. We're using a tiny bit of extra memory (the arrays) to save a huge amount of processing time—a classic space-time trade-off.

Optimising your code like this isn't just a programming trick; it's a structured way of thinking. This skill is valuable far beyond this puzzle, and you can explore more ways of honing it with our guide on how to improve problem-solving skills.

Supercharging Your Solver with Bitmasking

For the ultimate speed-up, we can turn to an advanced technique called bitmasking. This method represents the entire board's state using single numbers and performs checks with incredibly fast bitwise operations. Instead of arrays, we use integer variables where each bit corresponds to a column or diagonal.

Imagine an 8-bit integer, 00000000. To mark the third column as occupied, we just flip the third bit, making it 00000100. Checking if a column is free is as simple as a bitwise AND operation.

Here’s how it maps to our problem:

  1. Columns: An integer col_mask tracks occupied columns.
  2. Main Diagonals: An integer main_diag_mask tracks the main diagonals.
  3. Anti-Diagonals: An integer anti_diag_mask tracks the anti-diagonals.

When we place a queen at (row, col), we update these three masks using a bitwise OR. To backtrack, we just flip the bits back using XOR. This approach is ridiculously efficient because these operations are handled directly by the processor—they’re among the fastest things a computer can do.

While bitmasking is more complex to wrap your head around at first, the performance gain is enormous. For any N Queens problem where N is 32 or less (fitting neatly within standard integer types), a bitmasking solver will almost always smoke every other approach. It's a powerful lesson in how low-level thinking can create incredibly optimised code.

Bringing the N-Queens Solution to Life

Screenshot of a chess puzzle interface, showing a board with a black bishop, two white pawns, and game controls.

Let's be honest, algorithms can feel a bit abstract. They're just instructions locked away in code. To really get how a solver for the N-Queens problem works, you need to see it in action. Visualisation is what turns all that complex logic into something you can actually watch and understand.

Imagine seeing the backtracking algorithm exploring the chessboard. You’d watch it place a queen, then another, instantly highlighting all the newly attacked squares. When it hits a dead end, you’d see it literally "backtrack"—plucking a queen off the board to try a different spot. This kind of visual feedback makes the whole recursive process click in a way that staring at code never will.

Visualising the Backtracking Process

Simple diagrams or animations are brilliant for showing the algorithm's decision-making journey. When you can see the step-by-step exploration of every possibility, the core concepts stick.

Key moments to watch for:

  • Placement: A new queen appears on the board.
  • Conflict: Attacked rows, columns, and diagonals light up, showing why a certain square is off-limits.
  • Dead End: The algorithm gets to a column with no safe squares left.
  • Backtracking: The last queen is removed, and the algorithm steps back to the previous column to try a new path.

Watching this unfold makes it obvious how the algorithm smartly prunes entire branches of the decision tree, saving itself from pointless calculations.

Seeing an algorithm work is like watching a map being drawn in real-time. Instead of just being told the destination, you get to see every turn, every dead end, and every clever shortcut taken along the way. It turns abstract theory into a tangible story.

Building Your Own Interactive Game

One of the best ways to get a feel for the puzzle's constraints is to try solving it yourself. Building a simple, interactive N-Queens game is a fantastic little project. You don't need fancy graphics—just a basic grid where you can click to place and remove queens is plenty.

As you play, you’ll quickly build an intuition for the tricky patterns. This hands-on experience gives you a practical feel for the problem that nicely complements the theory. Trying to solve an 8x8 board by hand will definitely give you a new appreciation for the speed of a computerised solver.

If you enjoy this kind of challenge, you can try your hand at the interactive puzzles on Queens Game.

There are also tons of online visualisers that let you step through the N-Queens problem for different board sizes. They’re great for reinforcing the concepts we’ve discussed. You can control the speed and see exactly how the algorithm finds every single one of the 92 solutions for the classic 8x8 board.

Where N-Queens Thinking Shows Up in the Real World

You’re not going to find chess queens on a project management chart, but the thinking behind the N-Queens problem appears in some surprisingly practical places. The puzzle is a clean, simple model for a massive class of challenges known as Constraint Satisfaction Problems (CSPs). These are any problems where you have to find an outcome that follows a specific set of rules.

At its core, the N-Queens problem teaches you how to navigate competing constraints. Every queen you place restricts all your future choices. This is the same dynamic that pops up constantly in logistics, scheduling, and even circuit design. The skills you build solving it are directly transferable to the messy, complex scenarios that businesses face every day.

From Chessboards to University Timetables

A classic example of a CSP is university timetabling. Imagine trying to schedule hundreds of classes, each with its own non-negotiable rules.

  • A lecture hall can only host one class at a time (like a column on the board).
  • A professor can’t teach two different classes at once (like a row).
  • Certain student groups can’t have their required courses clash (like a diagonal).

Trying to organise this by hand is a logistical nightmare. But when you frame it as a CSP, algorithms similar to those for N-Queens can efficiently search for a valid timetable, saving administrators countless hours of headache.

The real power of the N-Queens problem isn’t finding a solution for one specific board. It’s about building a mental model for breaking down complex systems with interlocking rules into something you can actually solve, step by step.

More Applications of Constraint-Based Thinking

This logic stretches far beyond scheduling. The same principles are fundamental in many other fields, which shows just how versatile this way of thinking really is.

  • Resource Allocation: Assigning tasks to a team where each person has limited availability and specific skills. You have to distribute the work without overloading anyone or creating impossible dependencies.
  • Circuit Board Design: Placing components on a printed circuit board is a classic N-Queens-style puzzle. Components can’t be too close, and the tiny conductive paths can’t cross, creating a dense web of spatial constraints.
  • Computational Biology: In protein folding, scientists try to figure out the 3D structure of a protein. The different parts of the protein chain have to arrange themselves according to strict physical and chemical rules, a lot like queens on a board.

Tackling the N-Queens problem does more than just solve a puzzle. It sharpens your ability to think recursively, understand why one algorithm is better than another, and approach intimidating problems with a structured, methodical mindset. It’s a perfect example of why this "game" is still a cornerstone of a developer's education.

N-Queens FAQ: Your Questions Answered

When you first start wrestling with the N-Queens problem, a few questions tend to pop up again and again. Getting these sorted is key to building a solid foundation, so let’s tackle the most common ones.

Most people’s first question is about speed. We know the number of possible layouts gets huge, fast—so how do we actually measure an algorithm’s performance?

What Is the Time Complexity of a Backtracking Solution?

In the worst-case scenario, the backtracking algorithm has a time complexity of roughly O(N!), which you’d read as "O of N factorial." It’s a scary-looking number, and for good reason.

This is because the algorithm could, theoretically, try to place a queen in all N rows for the first column, then all remaining valid rows for the second, and so on. That factorial growth is precisely why brute-force becomes impossible for larger boards. While our optimisations cut down the search massively in practice, the theoretical upper limit remains punishingly high.

Can You Solve N-Queens Without Recursion?

Yes, absolutely. Recursion is a beautifully clean and intuitive way to model the problem, but you can definitely solve it iteratively. The standard way is by using a stack data structure to manage the process yourself.

Think of an iterative approach as manually doing what the function call stack does for you automatically. You push board states onto the stack as you place queens and pop them off when you need to backtrack. This method can even be more reliable in programming environments with strict limits on recursion depth.

The choice often boils down to clarity vs. control. Recursion gives you elegant, readable code. Iteration gives you direct power over memory and execution flow.

Does a Solution Exist for Every Board Size N?

Funnily enough, no. A solution to the N-Queens problem exists for all natural numbers except for N=2 and N=3. Go ahead and try it—it’s impossible to place two non-attacking queens on a 2x2 board, or three on a 3x3 board. You'll quickly see why.

But for a tiny 1x1 board and for all boards where N ≥ 4, you can always find at least one solution. From there, the number of unique solutions grows in a wild and often unpredictable pattern, which is part of what makes it such a classic mathematical puzzle.


Ready to put your own logic to the test? At Queens Game, we've turned this classic puzzle into a fun, interactive challenge. See if you can master the board and solve it yourself at https://queens.game.