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 nnnn
Example 1
Output: 2
Example 2
Output: 1
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
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
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 intcc
: attacked straight down from a queen in that column.cols : attacked along a down-right diagonal.diag : attacked along a down-left diagonal.anti
Bits are written with column 0 on the right, so 0010cols0010diag0100anti0001cols | diag | anti0111
The safe columns are the 0 bits, and ~intall = (1 << n) - 11111n = 4free = all & ~(cols | diag | anti)1000
Three boolean arrays, one for columns and one for each diagonal direction, would answer the same question and give a correct count. The int
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 colsdiag<< 1anti>> 1
The new queen's bit, bitcols | bit(diag | bit) << 1(anti | bit) >> 1bit = 1000cols = 1010anti = 0100diag11000
That extra bit is harmless, because allfree0001
Visiting only the safe columns
How does the loop walk through the 1 bits of freebit = free & -freex & -xfree -= bitfree
In the column 0 branch, row 1 has free = 110001001000
Java Solution
The method totalNQueens
- First,
starts the search by calling a helper method,totalNQueens , which handles one row per call: here row 0, and all three masks empty because no queen is on the board yet.place(n, 0, 0, 0, 0) - In
, ifplace equalsrow , every row has a queen, so return 1 for one solution.n - Otherwise build
, with n one bits, and the safe columns of this row,all . Start a counter,free = all & ~(cols | diag | anti) , at 0.count - A
loop takes the safe columns one at a time. Each round picks the lowest one aswhile , removes it frombit , and callsfree forplace with the queen's bit added and the diagonal masks shifted. The number that call returns is added torow + 1 .count - When
runs out, returnfree . 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.count
The mainn
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:
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: 2n = 1: 1n = 2n = 3
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 &freen = 4
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
nest one per row, at most n + 1 deep, and each holds a fewplace values and no arrays.int
To list the boards themselves instead of counting them, see