N-Queens II

Hard Recursion & Backtracking 2D Matrix Backtracking

N-Queens II is a hard recursion & backtracking problem solved with the 2d matrix backtracking pattern. The best approach, optimal (bitmask backtracking), runs in O(n!) time and O(n) space. Below are 3 approaches in Java, Python, C++ and JavaScript, from backtracking with board scanning up.

Problem

You are given an integer n. Place n queens on an n x n chessboard so that no two queens attack each other. A queen attacks every square in its own row, its own column and both of its diagonals, as far as the board goes.

Return the number of different layouts that satisfy this rule. Two layouts are different if some square holds a queen in one and not in the other.

Examples

Example 1

Input
n = 4
Output
2
Why
On a 4 by 4 board there are exactly two layouts: queens in columns 1, 3, 0, 2 (one per row, top to bottom) and its mirror image, columns 2, 0, 3, 1.

Example 2

Input
n = 1
Output
1
Why
A single queen on a single square attacks nothing, so there is one layout.

Example 3

Input
n = 3
Output
0
Why
Wherever the first queen goes, the second row has at most one safe square left, and after that the third row has none. No layout works.

Constraints

  • 1 <= n <= 9

Solve it here

Write your solution in Java, Python, C++ or JavaScript and run it against the examples, right in the page. Submit runs the hidden tests too and, with a free account, records the solve in your revision log.

00:00
Testcase

Run checks the testcases above (3 examples, or your own). Submit also runs 6 hidden tests and saves the solve to your log. Signed in, every Run and Submit is saved under My submissions; your draft stays in this browser.

Animated walkthrough

A narrated, step-by-step animation that builds the solution from the idea up. Press play, or step through it at your own pace.

Concepts first, then the problem and every approach, step by step.

Space to play or pause · ← → to jump a step · click or drag the bar to seek

Solutions

Try it yourself first. Then compare: each approach lists its idea, the steps, its time and space, and the code in Java, Python, C++ and JavaScript.

ApproachTimeSpace
Backtracking with board scanningO(n! · n)O(n)
Backtracking with column and diagonal setsO(n!)O(n)
Optimal (bitmask backtracking)O(n!)O(n)

1Backtracking with board scanning

TimeO(n! · n)The safe squares shrink row by row, so the search tree has at most about n! leaves, and every square tested costs O(n) to scan the earlier rows.
SpaceO(n)The cols array and the recursion stack are both n deep.

Put one queen in each row, top to bottom. Remember the column of the queen in every row so far. Before putting a queen at (row, col), look at every earlier row and check that its queen is not in the same column and not on a diagonal (the row gap equals the column gap). When the last row is filled, count one layout.

  1. cols[r] holds the column of the queen in row r.
  2. place(row): if row == n, every row has a queen, so return 1.
  3. For each col from 0 to n - 1, compare with every earlier row r: same column, or |row - r| == |col - cols[r]|, means it is attacked.
  4. If the square is safe, set cols[row] = col and add place(row + 1) to the total.
  5. Return the total. The answer is place(0).
class Solution {
    private int n;
    private int[] cols;

    public int totalNQueens(int n) {
        this.n = n;
        cols = new int[n];
        return place(0);
    }

    private int place(int row) {
        if (row == n) return 1;
        int count = 0;
        for (int col = 0; col < n; col++) {
            if (safe(row, col)) {
                cols[row] = col;
                count += place(row + 1);
            }
        }
        return count;
    }

    private boolean safe(int row, int col) {
        for (int r = 0; r < row; r++) {
            int c = cols[r];
            if (c == col || Math.abs(row - r) == Math.abs(col - c)) return false;
        }
        return true;
    }
}

2Backtracking with column and diagonal sets

TimeO(n!)The same search tree as before, but each square is now tested in O(1), so the work is about the number of nodes in the tree, at most about n!.
SpaceO(n)Three arrays of size at most 2n - 1, plus a recursion stack n deep.

Scanning the earlier rows repeats the same work again and again. Instead keep three boolean arrays: which columns are taken, which diagonals (row - col, shifted by n - 1 so it is never negative) are taken, and which anti-diagonals (row + col) are taken. A square is safe when all three are free, which is an O(1) check. Mark the three entries before going down a row and clear them when coming back.

  1. col[c], diag[row - c + n - 1] and anti[row + c] say whether a queen already uses that line. Each diagonal array has 2n - 1 slots.
  2. place(row): if row == n, return 1.
  3. For each c: skip it if any of the three entries is taken.
  4. Otherwise mark all three, add place(row + 1), then clear all three (backtrack).
  5. Return the total. The answer is place(0).
class Solution {
    private int n;
    private boolean[] col, diag, anti;

    public int totalNQueens(int n) {
        this.n = n;
        col = new boolean[n];
        diag = new boolean[2 * n - 1];
        anti = new boolean[2 * n - 1];
        return place(0);
    }

    private int place(int row) {
        if (row == n) return 1;
        int count = 0;
        for (int c = 0; c < n; c++) {
            int d = row - c + n - 1, a = row + c;
            if (col[c] || diag[d] || anti[a]) continue;
            col[c] = diag[d] = anti[a] = true;
            count += place(row + 1);
            col[c] = diag[d] = anti[a] = false;
        }
        return count;
    }
}

3Optimal (bitmask backtracking)

TimeO(n!)The same search tree, but each step finds the next safe square with a few bit operations instead of a loop over all columns.
SpaceO(n)Only the recursion stack, n levels deep, each holding three integers.

Pack the three sets into three integers, where bit c means column c of the current row is attacked. cols marks attacked columns. The diagonal masks need one more trick: a queen's down-right diagonal hits column c + 1 in the next row, so moving one row down shifts that mask left by one; the down-left diagonal shifts right by one. The free squares of a row are then ~(cols | left | right) & full, and the lowest set bit picks the next square to try.

  1. full = (1 << n) - 1 has a 1 for every column.
  2. solve(cols, left, right): if cols == full, every row has a queen, so return 1.
  3. free = ~(cols | left | right) & full holds the safe columns of this row.
  4. While free is not zero: bit = free & -free (the lowest safe column), remove it from free, and add solve(cols | bit, ((left | bit) << 1) & full, (right | bit) >> 1). The & full drops bits that slide off the board.
  5. Return the total. The answer is solve(0, 0, 0).
class Solution {
    private int full;

    public int totalNQueens(int n) {
        full = (1 << n) - 1;
        return solve(0, 0, 0);
    }

    private int solve(int cols, int left, int right) {
        if (cols == full) return 1;
        int count = 0;
        int free = ~(cols | left | right) & full;
        while (free != 0) {
            int bit = free & -free;
            free -= bit;
            count += solve(cols | bit, ((left | bit) << 1) & full, (right | bit) >> 1);
        }
        return count;
    }
}

Edge cases to test

  • n = 1 (one layout)
  • n = 2 and n = 3 (no layout at all, answer 0)
  • n = 6, where the count (4) is smaller than for n = 5 (10)
  • n = 9, the largest board, to make sure the search is fast enough

Hints

Hint 1

Two queens in the same row always attack each other, so every row holds exactly one queen. Place them one row at a time.

Hint 2

When you place a queen in row r, you only need to know which columns and which diagonals the queens above already use.

Hint 3

All squares on one diagonal share r - c, and all squares on one anti-diagonal share r + c. Three boolean arrays (or three bitmasks) answer "is this square safe?" in O(1).

FAQ

What is the best time complexity for N-Queens II?

Optimal (bitmask backtracking) runs in O(n!) time and O(n) extra space. The same search tree, but each step finds the next safe square with a few bit operations instead of a loop over all columns.

Which pattern does N-Queens II use?

It is a recursion & backtracking problem that uses the 2d matrix backtracking pattern. Other problems with the same pattern: Word Search, Robot Room Cleaner, Sudoku Solver.

Is there a brute force solution for N-Queens II?

Yes. Backtracking with board scanning takes O(n! · n) time and O(n) space. Put one queen in each row, top to bottom.

Which edge cases should I test for N-Queens II?

n = 1 (one layout); n = 2 and n = 3 (no layout at all, answer 0); n = 6, where the count (4) is smaller than for n = 5 (10); n = 9, the largest board, to make sure the search is fast enough.