N-Queens

Lesson 11.5 · Hard · Constraint search · 15 min · by Vinay C

We'll cover the following

Place n queens on an n by n board so that no two attack each other (same row, column, or diagonal).

Watch it run

Press Play or Step to walk through the example, or change the input and press Run. Each frame says what the algorithm does and why.

6 × 6 grid · 197 steps
Q·····
······
······
······
······
······

Row 0, column 0 is safe. Place a queen and move to row 1.

queens placed 1

1 / 197

The idea

Complexity

TimeSpaceWhy
O(n!) worst caseO(n)One queen per row, and the safety check prunes most columns.

In Python

def solve_n_queens(n):
    cols = []                                  # cols[r] = column of the queen in row r
    def safe(r, c):
        return all(c != c2 and abs(c - c2) != r - r2 for r2, c2 in enumerate(cols))
    def dfs(r):
        if r == n: return True
        for c in range(n):
            if safe(r, c):
                cols.append(c)
                if dfs(r + 1): return True
                cols.pop()                     # backtrack
        return False
    return cols if dfs(0) else None

Summary: say it in the interview

  • Place one queen per row. For each row try columns left to right and skip any square that is attacked. If a row has no safe square, go back to the previous row and move that queen. This is a search that undoes bad choices.
  • Time O(n!) worst case, space O(n). One queen per row, and the safety check prunes most columns.