CodingNodes / Backtracking / N-Queens II 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, count the ways to place n queens on an n × n board so that no two queens attack each other.

Return only the number of valid arrangements, not the boards themselves.

Constraints

  • 1 ≤ n ≤ 9

Examples: pick one to animate

Solutions

TimeO(n · n!) SpaceO(n)

Time: Each row tries at most n columns and every queen removes its column, so there are at most n! ways to fill the rows. Each safety check is three array lookups.

Space: Three boolean arrays of size about n and a recursion that is n deep. No boards are stored, only a counter.

Fill one row at a time. A square is safe when its column, its r − c diagonal and its r + c diagonal are all unused. Place the queen, mark the three, recurse into the next row, then unmark. Each time every row is filled, add one to count.