N-Queens
Place n queens on an n x n chessboard so that no queen can attack another, and list every way to do it.
Given a number nnn x n'Q''.'
Example 1
Output: [[".Q..", "...Q", "Q...", "..Q."], ["..Q.", "Q...", "...Q", ".Q.."]]
Example 2
Output: [["Q"]]
The Idea
In chess, a queen can move any number of squares along its row, its column or either of its two diagonals, so it threatens every square on those four lines. The puzzle asks for queens that leave each other alone: no queen may stand on a line of another. On the usual 8 x 8 board this is the old eight queens puzzle.
Look at the first answer of Example 1 and read it one string at a time, numbering rows and columns from 0. The string ".Q.."
How do we find such boards? Placing four queens on any four of the 16 squares can be done in 1,820 ways, and eight queens on 64 squares in 4,426,165,368 ways. Checking each of those is hopeless, so the search needs to throw away bad boards long before they are complete.
The rows give the first big cut. Two queens in one row attack each other, and there are nn
Sometimes a row has no such square left. Then the queens above it cannot be part of any solution, so we take back the last queen placed and try the next column in its row. Look at the picture below, which follows this search on the 4 x 4 board.
Start at the top box, the empty board, and take the left branch, row 0: column 0. In row 1, column 0 shares the queen's column and column 1 its diagonal, so the first free square is row 1: column 2. Under it, every square of row 2 is attacked, which is the orange box row 2: no safe column. The search backs up and moves the row 1 queen to column 3.
That branch gets one row further, to row 2: column 1, and then stops at row 3: no safe column. Rows 2 and 1 have no other free squares, so the search backs up all the way to row 0 and tries row 0: column 1. This time every row finds a free square, and the teal box at the bottom is the first board of Example 1.
A drawing like this, where each box is one choice and each path down from the top is one series of choices, is called a choice tree. Walking down it one queen at a time, and stepping back up as soon as a row has no free square, is called backtracking. For the 4 x 4 board, the whole search places a queen only 16 times, and finds the second board under the grey box row 0: columns 2, 3.
Solution Approach
Turning that search into code means settling three things: how to remember where the queens are, how to tell quickly whether a square is attacked, and how to take a queen back when the search backs up.
Remembering the queens
What does the search need to know about the queens placed so far? Since each row has one queen, a single number per row is enough: the column of its queen. An array named queenColqueenCol[r]r[1, 3, 0, 2]
Checking columns and diagonals
Is a square attacked? The simple check looks at every queen placed so far and compares columns and diagonals, which costs up to ncols
Diagonals need a way to name them. Moving one square down a "\" diagonal adds 1 to the row and 1 to the column, so row minus column stays the same along it. On the 4 x 4 board, row minus column is:
| column 0 | column 1 | column 2 | column 3 | |
|---|---|---|---|---|
| row 0 | 0 | -1 | -2 | -3 |
| row 1 | 1 | 0 | -1 | -2 |
| row 2 | 2 | 1 | 0 | -1 |
| row 3 | 3 | 2 | 1 | 0 |
Equal numbers run along the "\" diagonals: row 0, column 1, then row 1, column 2, then row 2, column 3 all have -1. The values go from -3 to 3, and an array index cannot be negative, so adding n - 1diag
Along a "/" diagonal, a step down adds 1 to the row and takes 1 from the column, so row plus column stays the same. It runs from 0 to 6 already, and indexes an array named anticolsdiaganti
Taking a queen back
How does the search back up? A method named placerowc
At that point the queen leaves: its three marks go back to false
Java Solution
The method solveNQueensplace
- First,
creates the listsolveNQueens , the arraysolutions of lengthqueenCol , and three boolean arrays:n withcols entries, andn anddiag withanti entries each, one per diagonal. Then it calls2n - 1 for row 0.place first checks whetherplace equalsrow . If it does, every row has a queen, and the helpern turnsdraw into strings, which go intoqueenCol .solutions- Otherwise, a loop moves
across the columns of this row. For each one it works out the diagonal indexesc andd = row - c + n - 1 , and skips the square ifa = row + c ,cols[c] ordiag[d] is marked.anti[a] - For a free square, it stores
inc , sets the three marks toqueenCol[row] , and callstrue forplace .row + 1 - When that call returns, it sets the three marks back to
and the loop goes on to the next column. Once the loop ends,false returns, and the search continues in the row above.place
The main
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class NQueens {
public static List<List<String>> solveNQueens(int n) {
List<List<String>> solutions = new ArrayList<>();
int[] queenCol = new int[n]; // queenCol[r] = column of the queen in row r
boolean[] cols = new boolean[n];
boolean[] diag = new boolean[2 * n - 1]; // index r - c + n - 1
boolean[] anti = new boolean[2 * n - 1]; // index r + c
place(n, 0, queenCol, cols, diag, anti, solutions);
return solutions;
}
private static void place(int n, int row, int[] queenCol, boolean[] cols, boolean[] diag,
boolean[] anti, List<List<String>> solutions) {
if (row == n) {
solutions.add(draw(queenCol)); // every row has a queen: a solution
return;
}
for (int c = 0; c < n; c++) {
int d = row - c + n - 1;
int a = row + c;
if (cols[c] || diag[d] || anti[a]) {
continue; // attacked: skip this square
}
queenCol[row] = c;
cols[c] = diag[d] = anti[a] = true; // place the queen
place(n, row + 1, queenCol, cols, diag, anti, solutions);
cols[c] = diag[d] = anti[a] = false; // take it back, try the next column
}
}
private static List<String> draw(int[] queenCol) {
List<String> board = new ArrayList<>();
for (int c : queenCol) {
char[] row = new char[queenCol.length];
Arrays.fill(row, '.');
row[c] = 'Q';
board.add(new String(row));
}
return board;
}
public static void main(String[] args) {
System.out.println(solveNQueens(4));
System.out.println(solveNQueens(1));
System.out.println(solveNQueens(2));
System.out.println(solveNQueens(3));
for (int n = 5; n <= 8; n++) {
System.out.println("n = " + n + ": " + solveNQueens(n).size() + " solutions");
}
}
}
Running it prints:
[[.Q.., ...Q, Q..., ..Q.], [..Q., Q..., ...Q, .Q..]]
[[Q]]
[]
[]
n = 5: 10 solutions
n = 6: 4 solutions
n = 7: 40 solutions
n = 8: 92 solutions
The 4 x 4 board gives the two boards of Example 1, in the order the search meets them: .Q....Q..Q..".Q.."[[Q]]
The two empty lists []
The + n - 1dd = row - cn = 4ArrayIndexOutOfBoundsException: Index -1 out of bounds for length 7
Complexity
The work is the number of queens the search places, times the column loop in each call to place
- Time: O(n ยท n!) at most, because row 0 has
columns to try, row 1 at mostn columns not already taken, and so on, while each call loops overn - 1 columns. The diagonal marks cut far more: forn the search callsn = 8 just 2,057 times.place - Space: O(n) besides the output, because
,queenCol ,cols anddiag hold at mostanti entries each, and the chain of waiting2n - 1 calls is at mostplace deep, one per row plus the final one. Each solution in the output takesn + 1 strings ofn characters.n
If you only need the number of solutions,