Show problems as
Classic problem #52HardBacktrackingAlgorithm X

N-Queens II

Real-world version: Counting the Safe Beacon Layouts
Tracked in this browser only
Read N-Queens II on LeetCode(opens in a new tab)

The statement here is our own: the same inputs, outputs and technique.

A square yard is laid out as n rows by n columns. A beacon placed in a cell sweeps its whole row, its whole column, and both diagonals running through it, for any distance.

Place n beacons on the yard so that no beacon stands in another's sweep. Return how many arrangements manage it.

Examples

Example 1

Input
n = 2
Output
0

On a two-by-two yard any two cells share a row, a column or a diagonal, so nothing works.

Example 2

Input
n = 6
Output
4

Four arrangements fit on a six-by-six yard, and each is a turn or a mirror image of the others.

Example 3

Input
n = 9
Output
352

Three hundred and fifty-two arrangements fit on a nine-by-nine yard.

Constraints

  • 1 <= n <= 9

The signature

The editor starts with this. It matches the parent problem's shape, so a solution that works here works on a standard judge unchanged.

Python
def total_n_queens(n: int) -> int:
Java
public int totalNQueens(int n)