CodingNodes / Backtracking / N Queens System design Space play · ←→ step · R restart

Problem

A queen attacks every square in her row, her column and both diagonals. Given an integer n, place n queens on an n × n board so that no two queens attack each other.

Return every valid arrangement. Each arrangement is a list of n strings, one per row, where "Q" marks a queen and "." an empty square. The arrangements may be returned in any order.

Constraints

  • 1 ≤ n ≤ 9

Examples: pick one to animate

Solutions

TimeO(n · n!) SpaceO(n)

Time: Each row has at most n columns to try, and every queen removes its column, so there are at most n! ways to fill the rows. The three lookups per column cost O(1), and drawing a board costs O(n²) but only happens for real answers.

Space: Besides the output, we store one column per row plus three boolean arrays of size about n, and the recursion is n deep.

Fill one row at a time, so two queens can never share a row. For the current row try each column. A square is safe when its column, its r − c diagonal and its r + c diagonal are unused, which is an O(1) array lookup. Place the queen, mark all three, recurse into the next row, then unmark. When every row has a queen, draw the board.