Solution: N-Queens

Let's solve the N-Queens problem using the Backtracking pattern.

Statement

Given a chessboard of size n×nn \times n, determine how many ways nn queens can be placed on the board, such that no two queens attack each other.

A queen can move horizontally, vertically, and diagonally on a chessboard. One queen can be attacked by another queen if both share the same row, column, or diagonal.

Constraints:

  • 1n91 \leq n \leq 9

Solution

So far, you’ve probably brainstormed some approaches and have an idea of how to solve this problem. Let’s explore some of these approaches and figure out which one to follow based on considerations such as time complexity and any implementation constraints.

Naive solution

In order to find the optimal placement of the queens on a chessboard, we could find all configurations with all possible placements of nn queens and then determine for every configuration if it is valid or not.

However, this would be very expensive, since there would be a very large number of possible placements and only a handful of valid ones. For example, when trying to place 66 queens on a 6×66 \times 6 chessboard using brute force, suppose we place the first two queens side by side on the first two squares, there still remain 34×33×32×31=111302434 \times 33 \times 32 \times 31 = 1113024 ...