N-Queens II

Count the ways to place n queens on an n by n chessboard so that no two attack each other.

A chess queen attacks every square in its own row, its own column and both of its diagonals. Given a number n, count the ways to place n queens on an n by n chessboard so that no queen attacks another. Two ways count as different when at least one queen stands on a different square.

Example 1
Input: n = 4
Output: 2
Example 2
Input: n = 1
Output: 1
Solution

The Idea

Take a 4 by 4 board and four queens. A queen attacks its whole row, so two queens can never share a row. Four queens in four rows means exactly one queen in each row. A placement is then just a choice of column for each row.

Number the rows 0 to 3 from the top and the columns 0 to 3 from the left, and try it by hand. Put the row 0 queen in column 0. In row 1, column 0 is attacked straight down and column 1 along the diagonal, so columns 2 and 3 are left. Pick column 2. Now every square of row 2 is attacked: columns 0 and 2 straight down, columns 1 and 3 along the diagonals of the row 1 queen.

That is a dead end, but it does not mean starting over. Only the latest choice was wrong, so go back one row and give the row 1 queen its next safe column, 3. Row 2 then has one safe column, 1, and after that row 3 has none. Another dead end. How many choices does this trial and error make before it has seen every answer?

Look at the picture below. It shows every board the search reaches for n = 4, with the queen just placed in orange and earlier queens in blue.

The full choice tree for n = 4. Row 0 tries columns 0 to 3. Columns 0 and 3 lead only to dead ends, where a row has no safe column. Column 1 leads to the solution with queens in columns 1, 3, 0, 2, and column 2 to the solution 2, 0, 3, 1.

The left branch, column 0, is the walk above: both of its paths end in a box marked "dead end". The branch for column 1 never has a choice to make. Row 1 has one safe column, 3, row 2 then has one, 0, and row 3 has one, 2: a solution. The branch for column 2 is its mirror image and gives the second solution. The branch for column 3 mirrors column 0 and ends in dead ends.

Counting the empty board, the search visits 17 boards and finds 2 solutions, which matches Example 1. Choosing a column row by row, and returning to the previous row to try its next column whenever a row has no safe column, is called backtracking. A dead end cuts off everything below it: after column 0 and then column 2, no queen is ever placed in row 2 or row 3.

This problem only wants the number of solutions, not the boards. So when the last row gets its queen, the search adds 1 to a count, and each choice reports how many solutions lie below it. What remains is to find the safe columns of a row quickly.

Solution Approach

Turning this row-by-row search into code starts with why it beats trying every placement, then settles three things: how to record which columns of a row are attacked, how those attacks change from one row to the next, and how to visit only the safe columns.

Trying every placement

Why not simply try every way to put the queens down and check each one? Four queens can sit on 16 squares in 1,820 ways, and eight queens on 64 squares in 4,426,165,368 ways. Even with one queen per row, an 8 by 8 board has 88, or 16,777,216, column choices. The row-by-row search for n = 8 visits 2,057 boards, because each dead end removes all the choices below it.

Recording the attacked columns as bits

How does the search know which columns of the next row are safe? A queen placed above can reach a square in three ways: straight down its column, along the diagonal that runs down to the right (\), or along the diagonal that runs down to the left (/). Three int values keep one bit per column, and a 1 in bit c means column c of the current row is attacked that way:

  • cols: attacked straight down from a queen in that column.
  • diag: attacked along a down-right diagonal.
  • anti: attacked along a down-left diagonal.

Bits are written with column 0 on the right, so 0010 means column 1. Take the branch for column 1 in the picture: the queen in row 0, column 1. For row 1, cols is 0010, diag is 0100 (column 2) and anti is 0001 (column 0). Their OR, cols | diag | anti, is 0111: columns 0, 1 and 2 are attacked for one reason or another.

The safe columns are the 0 bits, and ~ flips every bit to get them as 1s. But an int has 32 bits, and the 28 bits above the board flip to 1 too, looking like columns that do not exist. ANDing with all = (1 << n) - 1, which is 1111 for n = 4, clears them. So free = all & ~(cols | diag | anti) is 1000: column 3 is the one safe square, as the picture shows under column 1.

Three boolean arrays, one for columns and one for each diagonal direction, would answer the same question and give a correct count. The int masks find every safe column of a row in one expression instead of checking the columns one by one.

Moving the attacks down one row

What happens to the masks when the search moves down a row? An attack straight down stays in its column, so cols passes on unchanged. A down-right attack lands one column further right, a higher column number, which is one bit further left: diag shifts left with << 1. A down-left attack lands one column lower, so anti shifts right with >> 1.

The new queen's bit, bit, joins each mask before the shift: cols | bit, (diag | bit) << 1 and (anti | bit) >> 1. Follow the column 1 branch one row further, with the row 1 queen in column 3, bit = 1000. Row 2 gets cols = 1010 and anti = 0100. diag becomes 11000, with one bit past the board's edge.

That extra bit is harmless, because all cuts it off, and a bit shifted right past column 0 simply drops out of the number. Row 2's free comes out as 0001, column 0, the next board down in the picture.

Visiting only the safe columns

How does the loop walk through the 1 bits of free without testing all n columns? bit = free & -free keeps only the lowest 1 bit, the safe column with the smallest number. Single Number III shows why x & -x does that. Then free -= bit removes it, and the loop stops when free is 0.

In the column 0 branch, row 1 has free = 1100. The first round takes 0100, column 2, and the second takes 1000, column 3, the same left-to-right order as the two boards under column 0 in the picture.

Java Solution

The method totalNQueens works in these steps:

  1. First, totalNQueens starts the search by calling a helper method, place(n, 0, 0, 0, 0), which handles one row per call: here row 0, and all three masks empty because no queen is on the board yet.
  2. In place, if row equals n, every row has a queen, so return 1 for one solution.
  3. Otherwise build all, with n one bits, and the safe columns of this row, free = all & ~(cols | diag | anti). Start a counter, count, at 0.
  4. A while loop takes the safe columns one at a time. Each round picks the lowest one as bit, removes it from free, and calls place for row + 1 with the queen's bit added and the diagonal masks shifted. The number that call returns is added to count.
  5. When free runs out, return count. A row with no safe column returns 0, which is a dead end. The masks are arguments, so each call has its own copies and stepping back needs no clean-up.

The main method runs both examples, the boards of size 2 and 3, the classic 8 by 8 board, and the counts for n from 1 to 12.

Java
public class NQueensII {

    public static int totalNQueens(int n) {
        return place(n, 0, 0, 0, 0);
    }

    // cols, diag and anti have a 1 bit for each column attacked in the current row
    private static int place(int n, int row, int cols, int diag, int anti) {
        if (row == n) {
            return 1;                                 // every row has a queen
        }
        int all = (1 << n) - 1;                       // n one bits, one per column
        int free = all & ~(cols | diag | anti);       // columns in this row that are safe
        int count = 0;
        while (free != 0) {
            int bit = free & -free;                   // the lowest safe column
            free -= bit;
            // one row down, down-right attacks move one column up, down-left ones one down
            count += place(n, row + 1, cols | bit, (diag | bit) << 1, (anti | bit) >> 1);
        }
        return count;
    }

    public static void main(String[] args) {
        System.out.println("n = 4: " + totalNQueens(4));
        System.out.println("n = 1: " + totalNQueens(1));
        System.out.println("n = 2: " + totalNQueens(2));
        System.out.println("n = 3: " + totalNQueens(3));
        System.out.println("n = 8: " + totalNQueens(8));
        StringBuilder sb = new StringBuilder("n = 1 to 12:");
        for (int n = 1; n <= 12; n++) {
            sb.append(n == 1 ? " " : ", ").append(totalNQueens(n));
        }
        System.out.println(sb);
    }
}

Running it prints:

Output
n = 4: 2
n = 1: 1
n = 2: 0
n = 3: 0
n = 8: 92
n = 1 to 12: 1, 0, 0, 2, 10, 4, 40, 92, 352, 724, 2680, 14200

n = 4: 2 and n = 1: 1 match the examples. For n = 2 and n = 3 the count is 0: those boards are too small, and every branch of the search ends in a dead end. The 8 by 8 board, the size of a real chessboard, has 92 solutions.

Look at the last line: the counts do not grow steadily. A 6 by 6 board has 4 solutions, fewer than the 10 of a 5 by 5 board, and from there the counts climb fast, to 14,200 for n = 12.

The all & in the line that builds free matters. Without it, the bits above the board count as safe columns, and the same search for n = 4 returns 581,890 instead of 2.

Complexity

The cost is the number of boards the search visits, with a few bit operations on each.

  • Time: O(n!) at most, because row 0 has n columns to try, row 1 at most n - 1 unused columns, row 2 at most n - 2, and so on, and dead ends cut most branches short.
  • Space: O(n), because the calls of place nest one per row, at most n + 1 deep, and each holds a few int values and no arrays.

To list the boards themselves instead of counting them, see N-Queens.