Vibe Engines
YouTube

Vibe Engines is free, interactive AI engineering & system design — runs in your browser. Pick a learning path

ALGORITHMS · 17  /  N-QUEENS

The Standoff.

Put four queens on a board so no two can attack — no shared row, column, or diagonal. There's no formula, only search: place a queen, try to build on it, and when you hit a dead end, undo and try again. That undo is backtracking.

THE GIST · 20 SECONDS

N-Queens places one queen per column, left to right. In each column, try each row: a row is safe if no earlier queen shares its row or a diagonal. On a safe square, place and recurse to the next column. If a column has no safe row, backtrack — pull the previous queen and try its next spot. Fill all N columns and you've solved it.

  • Backtrackundo a bad choice
  • Safeno row / diagonal clash
  • Recursesolve the next column
  • Pruneabandon dead branches

Hit Step to try the next square — or Play and watch the search place, clash, backtrack, and finally solve it.

UNDER THE HOOD

What you just played, written down

Backtracking is depth-first search with an undo button. Make a choice, dive deeper, and the moment a partial answer can't work, rewind to the last decision and take the other road.

How backtracking thinks — four moves

  1. One choice at a time. Fill columns left to right; each column needs exactly one queen, in some row.
  2. Check before you commit. A row is safe only if no placed queen shares that row or either diagonal.
  3. Place & recurse. On a safe square, place the queen and solve the next column. Success there means success here.
  4. Dead end? Undo. If no row in a column is safe, remove the previous queen and try its next row — backtrack.
WHY UNDOING IS THE WHOLE IDEA

A wrong early queen poisons every arrangement built on top of it. Rather than test them all, backtracking abandons the whole branch the instant it's doomed — then quietly restores the board and tries the next option.

The whole thing in code

def solve(n):
    pos = [-1] * n          # pos[col] = row of its queen

    def safe(col, row):
        for c in range(col):
            r = pos[c]
            if r == row or abs(r - row) == abs(c - col):
                return False     # same row or diagonal
        return True

    def place(col):
        if col == n:
            return True          # all columns filled - solved
        for row in range(n):
            if safe(col, row):
                pos[col] = row   # choose
                if place(col + 1):
                    return True  # recurse
                pos[col] = -1    # UNDO - backtrack
        return False

    return pos if place(0) else None
TIMEO(N!)worst case, heavily pruned
SPACEO(N)recursion + board
PRUNING BEATS BRUTE FORCE

Checking safety before recursing means a doomed placement never spawns its subtree. That early failure is what makes backtracking search the whole space without visiting the whole space.

⚠ Still exponential

Pruning helps enormously but the worst case is super-polynomial. For large N you add smarter heuristics (most-constrained column first) or switch to specialised methods; backtracking is general, not always fast.

↔ One queen per column, by design

Two queens in one column would attack instantly, so we bake that constraint in — one per column — and only ever search over rows. Fewer choices, faster search.

★ Where it's used

Sudoku and constraint puzzles, permutations/combinations, subset-sum, maze solving, graph coloring, and parsing — anywhere you build incrementally and can detect a dead end early.

The picture: how much search pruning saves

QQQQfirst solution found, 4 queens012318242314043445568655073128928 queens: partial boards after k columnssafe
Left: the first solution backtracking reaches for 4 queens, with pos = [1, 3, 0, 2] (the row of the queen in each column). Right: for 8 queens, the bars show how many partial boards exist after each column when unsafe squares are rejected immediately (highlighted bars) against k queens in k distinct rows with no safety test (plain bars, log scale; the counts are listed in the description). The numbers under the bars are the safe counts. The pruned search peaks at 568 boards after column 5 and ends at the 92 solutions.

Worked example, step by step

Run the page's own code on n = 4, trying rows 0 to 3 in each column in order. The Board column shows pos after the step: the row of the queen in each column, with · for an empty column. The search stops at the first solution.

StepActionBoardWhy
1place column 0, row 00 · · ·safe
2place column 1, row 20 2 · ·safe
3undo column 1, row 20 · · ·column 2 had no safe row
4place column 1, row 30 3 · ·safe
5place column 2, row 10 3 1 ·safe
6undo column 2, row 10 3 · ·column 3 had no safe row
7undo column 1, row 30 · · ·column 2 had no safe row
8undo column 0, row 0· · · ·column 1 had no safe row
9place column 0, row 11 · · ·safe
10place column 1, row 31 3 · ·safe
11place column 2, row 01 3 0 ·safe
12place column 3, row 21 3 0 2safe

The search placed 8 queens, undid 4 of them and tested 26 squares in total before finishing, where a blind search of one queen per column would have 4⁴ = 256 boards to consider. The first choice, a queen at row 0 of column 0, is doomed, and steps 3, 6, 7 and 8 are the four undos needed to prove it. Every board with that queen is eliminated at once, so the search never builds them. The second branch (row 1) goes straight to the answer. Counting instead of stopping, the same search finds both solutions for 4 queens, [1, 3, 0, 2] and [2, 0, 3, 1].

Complexity and trade-offs

CaseTimeSpaceWhy
Backtracking, column by columnexponential; 2,056 placements for n = 8, 35,538 for n = 10O(n)Each placement checks earlier queens, O(n) per check, so 15,720 safety tests for n = 8. Space is the recursion depth plus pos.
Same tree, constant-time checkssame placements, O(1) per checkO(n)Keep sets (or bitmasks) of used rows, r − c diagonals and r + c diagonals instead of scanning.
One queen per row and column, then testO(n · n!)O(n)Generate permutations (40,320 for n = 8) and check diagonals at the end.
One queen per column, any rowO(n · nⁿ)O(n)nⁿ = 16,777,216 boards for n = 8; hopeless beyond small n.

The solution counts for n = 1 to 10 are 1, 0, 0, 2, 10, 4, 40, 92, 352 and 724; they do not grow smoothly. The number of placements grows by a factor of roughly 4 per step (2,056 at n = 8, then 8,393, then 35,538). The trade-off is generality against speed: the plain version is a few lines and works for any constraint you can test incrementally. Specialised bitmask versions are faster but only fit this problem.

Common mistakes

  • Checking only one diagonal direction

    Testing q − k == r − c but forgetting the anti-diagonal lets attacking pairs through. The count for 4 queens comes out as 7 instead of 2, and for 8 queens as 2113 instead of 92.

  • Stopping at the first solution when you meant to count

    The page's place returns True as soon as one board is complete, which is right for "find a solution". Reusing the same shape to count gives 1 for 8 queens. To count, make the recursion return nothing (or a count) and keep going after a success.

  • Forgetting to undo the row and diagonal sets

    With a row set and two diagonal sets, every placement must remove its entries after the recursive call returns. If you only add, the sets fill up and the count for 4 queens, and for 8, is 0. The page's array version looks like it needs no undo because it only reads earlier columns, but resetting pos[col] is still the safe habit.

  • Scanning all columns instead of the earlier ones

    If pos starts at −1 and the safety check loops over every column, the −1 entries are treated as queens. The check then rejects squares for no reason and the count is 0 for both 4 and 8 queens. Loop only over range(col).

  • Negative indexes in a diagonal array

    In Python, d1[r − c] with d1 = [0] * n does not fail when r − c is negative; it silently wraps to the end of the list and shares a slot with a different diagonal. That version returned 0 for both n = 4 and n = 8 here. Offset the index by n − 1 and allocate 2n − 1 slots.

Where this shows up

  • Constraint satisfaction

    N-Queens is the standard small example of a constraint satisfaction problem: variables (the row of each column), a domain per variable, and pairwise constraints. General CSP and SAT solvers add constraint propagation and smarter variable ordering on top of the same try, check, undo loop.

  • Testing search code

    Because the solution counts are known (92 for n = 8, 724 for n = 10), it is a handy test for search strategies and optimisations: a wrong count is immediately visible.

  • Scheduling with conflicts

    Timetabling and resource assignment have the same shape: assign one slot per item so that no two conflicting items clash, and abandon a partial assignment the moment a conflict appears.

SOLVE IT YOURSELF

Solve it: count N-Queens solutions

This one is yours to write — in Python or TypeScript, running for real in your browser. Backtrack column by column and count every full solution. Edit the stub, hit Run (or ⌘/Ctrl + Enter), and watch the hidden tests. Stuck? the hints are below and Reveal solution is one click away.

YOUR TASK

Implement count_queens(n): return how many distinct ways N queens can be placed on an N×N board so no two attack each other. Use backtracking — place one queen per column and count the completed boards.

HINTS — 4 IDEAS
  1. Track pos[col] = row for placed queens; place one column at a time.
  2. safe(col, row): no earlier queen shares the row (r == row) or a diagonal (abs(r-row) == abs(c-col)).
  3. When col == n, you've filled every column — that's one solution, add 1.
  4. After recursing, undo the choice (or just don't persist it) and try the next row.
CPython · WebAssembly
QUICK CHECK

Did it stick?

See every answer, with the reasoning
  1. What does "backtrack" mean in this algorithm?

    Answer: Undo the most recent queen and try its next row — When a column has no safe row, the current branch is doomed. Backtracking removes the previous column’s queen and continues trying its remaining rows — undoing one decision, not the whole board.

  2. When is a square considered safe to place a queen?

    Answer: When no earlier-column queen shares its row or a diagonal — Since we place one queen per column, columns can’t clash. A square is safe only if no already-placed queen shares its row (r == row) or a diagonal (abs(r-row) == abs(c-col)).

  3. Why is backtracking faster than checking every arrangement?

    Answer: It prunes — a doomed partial placement never explores its subtree — By checking safety before recursing, a bad placement is abandoned immediately along with all the arrangements that would sit beneath it. That pruning skips huge parts of the search space.

FAQ

N-Queens, answered

What is the N-Queens problem?

Place N queens on an N×N board so no two attack — no shared row, column, or diagonal. It's the classic puzzle used to teach backtracking.

What is backtracking?

Depth-first search with an undo: build a solution one choice at a time, and abandon a partial candidate the moment it can't be completed — then rewind and try the next option.

How does it solve N-Queens?

Place one queen per column, left to right. Try each row; if safe, place and recurse to the next column; if a column has no safe row, remove the previous queen and try its next row.

Why is it faster than brute force?

It prunes: a doomed partial placement never spawns its subtree, so huge regions of arrangements are skipped. The worst case is still exponential, but far fewer boards are actually visited.

Where else is backtracking used?

Sudoku, permutations/combinations, subset-sum, maze solving, graph coloring, regex matching, and parsing — anywhere you build incrementally and can spot a dead end early.

RESULT

—

Next → the exact same try-recurse-undo skeleton solves Sudoku, generates every permutation, and colors graphs. Learn backtracking once, reuse it everywhere.

Finished this one? 0 / 99 Algorithms done
NextGuess, Hit a Wall, Erase: Sudoku Solver Next on the “Try, fail, undo” ladder · rung 4 of 4

Explore the topic

See this alongside everything else on the same subject — handbooks, system designs, challenges and tools, in one place.

More Algorithms