Quick Answer

N queens problem asks you to place n queens on an n by n board. No queen can attack another queen. Backtracking solves it in 3 moves. They are place, check and undo. A 4 by 4 board has 2 solutions. An 8 by 8 board has 92. Python and C++ code below was executed.

N queens problem is the classic way to meet backtracking. Most tutorials show only the path that works and hide the dead ends.

Dead ends are the lesson. This guide traces a real search on a 4 by 4 board with every undo step visible.

What Is the N Queens Problem?

Queens attack along a row, a column and both diagonals. The task is to place n queens on an n by n board so that no queen attacks another.

Counts below come from the Python code in this guide. They were also checked against a brute force count for boards up to 8 by 8.

Board size nSolutions
11
20
30
42
510
64
740
892
9352
10724

Standard 8 by 8 boards have 92 solutions. Only 12 are distinct when you ignore rotations and mirror images. Boards of size 2 and 3 have no solution so 4 by 4 is the smallest real puzzle.

What Is Backtracking?

The backtracking algorithm tries choices one at a time and undoes a choice that leads nowhere. Make a move and check whether it can still work.

If yes then go deeper. If no then take the move back and try the next option.

Picture a maze. You choose a path and reach a dead end. You walk back to the last fork and try another branch.

This backtracking algorithm is recursion with an undo step. Full reference sits in the backtracking lesson.

Which 2 Approaches Solve the N Queens Problem?

Table below compares both approaches for n of 8. Backtracking count is the number of queen placements the tested code tried while counting all 92 solutions.

ApproachWork at n of 8
Approach #1 Brute force over every column choice16,777,216 arrangements (8 to the power 8)
Approach #2 Backtracking (fewest checks)2,056 placements

Approach #1: Brute Force (Try Every Arrangement)

What you get. A correct but wasteful method. Place a queen in every row in every possible column and then test the full board.

Approach #2: Backtracking (Check Early and Undo)

What you get. A search that drops bad boards early. Check every queen the moment you place it and undo the placement when a row has no safe square. This backtracking algorithm saves most of the work.

How Does Backtracking Solve the N Queens Problem Step by Step?

Place one queen per row and try columns from left to right. Every new queen must be safe from the queens above it. Rows and columns start at 0.

Table below lists every placement and removal of the tested code on a 4 by 4 board. Event 3 is the first dead end.

EventActionRowColumnReason
1Place00Board is empty
2Place12Columns 0 and 1 are attacked
3Remove12Every row 2 square is attacked
4Place13Next column in row 1
5Place21Safe below both queens
6Remove21Every row 3 square is attacked
7Remove13Row 2 has no other column
8Remove00Row 1 has no other column
9Place01Next column in row 0
10Place13Safe from the first queen
11Place20Safe from both queens
12Place32Board is filled

Row 2 shows the dead end. Queens sit at row 0 column 0 and row 1 column 2 so every square in row 2 is attacked.

Columns 0 and 2 are attacked down the file. Columns 1 and 3 are attacked on diagonals.

Events 7 and 8 matter most. No solution starts with a queen in column 0 on this board so the search removes every queen and moves the first queen to column 1. Final board has queens in columns 1, 3, 0 and 2.

How Do You Code the N Queens Problem in Python and C++?

Python version below has a safety check, a function that finds one solution and a function that counts all solutions. Board stores one column number per row.

def is_safe(board, row, col):
    for r in range(row):
        c = board[r]
        if c == col or abs(c - col) == row - r:
            return False
    return True


def solve(board, row, n):
    if row == n:
        return True
    for col in range(n):
        if is_safe(board, row, col):
            board[row] = col
            if solve(board, row + 1, n):
                return True
            board[row] = -1
    return False


def count_solutions(board, row, n):
    if row == n:
        return 1
    total = 0
    for col in range(n):
        if is_safe(board, row, col):
            board[row] = col
            total += count_solutions(board, row + 1, n)
            board[row] = -1
    return total

C++ version below finds one solution for a 4 by 4 board. The line that sets a row back to -1 is the undo step.

#include <cstdlib>
#include <iostream>
#include <vector>

bool isSafe(const std::vector<int>& board, int row, int col) {
    for (int r = 0; r < row; r++) {
        int c = board[r];
        if (c == col || std::abs(c - col) == row - r) return false;
    }
    return true;
}

bool solve(std::vector<int>& board, int row, int n) {
    if (row == n) return true;
    for (int col = 0; col < n; col++) {
        if (isSafe(board, row, col)) {
            board[row] = col;
            if (solve(board, row + 1, n)) return true;
            board[row] = -1;
        }
    }
    return false;
}

int main() {
    int n = 4;
    std::vector<int> board(n, -1);
    if (solve(board, 0, n)) {
        for (int c : board) std::cout << c << " ";
        std::cout << "\n";
    }
    return 0;
}

Tested. Python 3.13.18 found [1, 3, 0, 2] for n of 4 and a valid board for n of 8.

It reported no solution for n of 2 and 3. g++ 13.3 compiled the C++ sample with warnings on and printed 1 3 0 2. Tests ran in a cloud sandbox.

What Is the Time Complexity of the N Queens Problem?

Worst case time is bounded by O(n factorial) because every placed queen uses one column. Space is O(n) since the board stores one column per row.

Real work is far below that bound. Table below counts queen placements while the code searches for all solutions.

nPlacements triedn factorial
6152720
82,05640,320
1035,5383,628,800

Counting all solutions with the best of 3 trials in CPython 3.13.18 took 0.004 s for n of 8 and 0.019 s for n of 9. Size 10 took 0.099 s. Work grows quickly as n rises.

Why Learn the N Queens Problem?

You will almost never place queens at work. Still the place, check and undo loop appears in many problems. Constraint puzzles like Sudoku and word search use the same shape.

Practice more problems in the backtracking practice set. Backtracking is one stage of the DSA roadmap and the recursion lesson is the base for it.

Frequently Asked Questions

What Is the N Queens Problem in Plain Words?

It asks you to place n queens on an n by n chessboard so that no 2 queens attack one another. No 2 queens can share a row, a column or a diagonal.

How Many Solutions Does the 8 Queens Problem Have?

There are 92 solutions on a standard 8 by 8 board. Only 12 are distinct when rotations and mirror images count as the same.

What Is Backtracking in the N Queens Problem?

The backtracking algorithm removes the last queen after a dead end and tries the next column. That undo makes recovery possible.

Why Does the N Queens Problem Use Recursion?

Every row is a smaller version of the same task. One call handles a row and then calls the function for the next row.

What Is the Smallest Board With a Solution?

Size 1 works trivially. Sizes 2 and 3 have none. Size 4 is the smallest real puzzle with 2 solutions.

How Does the Search Cost Grow?

Worst case time is bounded by O(n factorial) and space is O(n). Tested counts remain far below that bound and still grow quickly.

Does a First Queen in Column 0 Always Lead to a Solution?

No. Size 4 has no solution that starts at row 0 column 0. The search removes that queen and tries column 1.

What Should You Remember About the N Queens Problem?

Place a queen, check it and go deeper. Undo as soon as a row has no safe square. This backtracking algorithm solves many puzzles.

Key takeaways.

  • Size 4 has 2 solutions and size 8 has 92.
  • Backtracking tried 2,056 placements where brute force needs 16,777,216 arrangements.
  • Undo is the core of the backtracking algorithm.

Check yourself. With the first queen at row 0 column 1 on size 4 the first safe column in row 1 is 3.