N-queens

None attacks another · Part of Strategies

Key idea

Practice

6 questions · about 3 min

Explained step by step

N-queens

In chess, a queen attacks any piece in its same row, column or diagonal. The n-queens problem asks you to place n queens on an n × n board so that none attacks another. With 4 queens there are 2 solutions; with 8, there are 92. In backtracking, the options are the squares, and the state is what the board looks like at each moment.

Diagonals run in 2 directions. On a main diagonal (\), row − column is always the same number: (0, 0), (1, 1) and (2, 2) give 0. On a secondary one (/), what stays constant is row + column: (0, 2), (1, 1) and (2, 0) give 2. That way, 2 lists, diags1 and diags2, mark which diagonals have a queen. On an n × n board there are 2n − 1 diagonals of each kind: with 8 × 8, 15.

Pruning

There are n queens and n rows, and 2 queens cannot share a row: so each row has exactly 1 queen. They are therefore placed 1 per row, from the first to the last. This is already a pruning: it rules out from the start every branch with 2 queens in the same row. Instead of choosing among n² squares per queen, you choose among n columns.

To keep 2 queens from sharing a column, a list of booleans cols of length n is used: cols[c] says whether column c already has a queen. Before placing a queen, cols is checked to skip taken columns. Placing the queen sets it to True, and going back sets it to False. With this pruning, row 0 has n options, row 1 has n − 1, and so on: n! in total.

Backtracking

With 4 queens, the search first tries the row 0 queen in column 0. From there, the following rows run out of spots and it has to go back. With the row 0 queen in column 1, row 1 goes to column 3, row 2 to column 0 and row 3 to column 2: that is the first solution. The other is its mirror: columns 2, 0, 3 and 1.

Time complexity

n placements are made, 1 per row. The column pruning leaves n, n − 1, ..., 2 and 1 options per row: O(n!). Saving a solution copies the board, O(n²). The total time is O(n! × n²), although the diagonal pruning shrinks it a lot in practice. In memory, the board takes O(n²), cols, diags1 and diags2 take O(n) each, and the recursion goes n levels deep: O(n²) in total.

Terms in this lesson

Arki, the beaver mascot

Your next interview starts with 5 minutes today.

Free on iOS and Android. Start from zero, no account needed.

Key idea

None attacks another