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 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 row, its column and both of its diagonals. Return every distinct solution, each drawn as a list of strings, one string per row, where 'Q' is a queen and '.' is an empty square.

Example 1
Input: n = 4
Output: [[".Q..", "...Q", "Q...", "..Q."], ["..Q.", "Q...", "...Q", ".Q.."]]
Example 2
Input: n = 1
Output: [["Q"]]
Solution

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.." is row 0, with its queen in column 1. The next three rows have their queens in columns 3, 0 and 2. Every row and every column holds one queen, and no two queens share a diagonal.

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 n queens for n rows, so each row gets exactly one queen. Instead of picking squares, we pick a column for row 0, then a column for row 1, and so on. Each new queen goes only on a square that the queens above it do not attack.

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.

Part of the choice tree for n = 4. Row 0: column 0 leads to two dead ends, row 2: no safe column and row 3: no safe column, where the search backs up. Row 0: column 1, then row 1: column 3, row 2: column 0 and row 3: column 2 reach the first solution.

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 queenCol holds them, so queenCol[r] is the column of the queen in row r. For the first board of Example 1 it is [1, 3, 0, 2], and the strings are drawn from it only when a board is complete.

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 n steps per square. Rows need no check at all, because each row gets its one queen and the search then moves to the next row. Columns are easy too: a boolean array cols marks the columns that already have a queen.

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 0column 1column 2column 3
row 00-1-2-3
row 110-1-2
row 2210-1
row 33210

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 - 1, here 3, turns them into indexes 0 to 6 of an array named diag.

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 anti. A square is attacked when its entry in cols, diag or anti is marked, which is three lookups instead of a pass over the earlier queens.

Taking a queen back

How does the search back up? A method named place handles one row: it tries each free column, marks it, and calls itself for the next row. A method that handles row 1 by calling itself for row 2 is called recursive. Each call still waiting for the rows below keeps its own row number, row, and the column it is trying, c. When the call for the next row returns, every board under that queen has been tried.

At that point the queen leaves: its three marks go back to false, so its column and diagonals are free again for the next column in the same row. Without this step, column 0 would stay blocked after row 0: column 0 was given up, and the branches under row 0: column 1 could never use it.

Java Solution

The method solveNQueens and its helper place work in these steps:

  1. First, solveNQueens creates the list solutions, the array queenCol of length n, and three boolean arrays: cols with n entries, and diag and anti with 2n - 1 entries each, one per diagonal. Then it calls place for row 0.
  2. place first checks whether row equals n. If it does, every row has a queen, and the helper draw turns queenCol into strings, which go into solutions.
  3. Otherwise, a loop moves c across the columns of this row. For each one it works out the diagonal indexes d = row - c + n - 1 and a = row + c, and skips the square if cols[c], diag[d] or anti[a] is marked.
  4. For a free square, it stores c in queenCol[row], sets the three marks to true, and calls place for row + 1.
  5. When that call returns, it sets the three marks back to false and the loop goes on to the next column. Once the loop ends, place returns, and the search continues in the row above.

The main method runs both examples, the 2 x 2 and 3 x 3 boards, and then prints only the number of solutions for boards of size 5 to 8.

Java
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:

Output
[[.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.. first, from row 0: column 1, then its mirror image ..Q., from column 2. A list prints its strings without quotes, so .Q.. is the string ".Q..". The 1 x 1 board has the single queen [[Q]].

The two empty lists [] come from the 2 x 2 and 3 x 3 boards, where every branch runs into a row with no free square. The counts below them do not grow steadily: 6 x 6 has only 4 solutions, fewer than the 10 of 5 x 5, and the eight queens puzzle has 92.

The + n - 1 in d matters. With d = row - c alone, the search for n = 4 stops at row 1, column 2, whose row minus column is -1, and Java throws ArrayIndexOutOfBoundsException: 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 n columns to try, row 1 at most n - 1 columns not already taken, and so on, while each call loops over n columns. The diagonal marks cut far more: for n = 8 the search calls place just 2,057 times.
  • Space: O(n) besides the output, because queenCol, cols, diag and anti hold at most 2n - 1 entries each, and the chain of waiting place calls is at most n + 1 deep, one per row plus the final one. Each solution in the output takes n strings of n characters.

If you only need the number of solutions, N-Queens II does the same search with bitmasks and skips drawing the boards.