618. Queens Count

Hard7.5 points estimatedBacktracking3 hints

A park designer places n watchtowers on an n x n square of land. Two towers see each other if they share a row, a column or a diagonal, and a valid layout has no pair of towers that see each other.

Return the number of different valid layouts that put exactly one tower in every row. Two layouts differ if some cell holds a tower in one but not the other. A solution that lists every layout and counts them is allowed, but one that tracks attacked columns and diagonals with bit masks is much faster and is expected to finish within the time limit for the largest n.

Example 1

Input:
n = 4
Output:
2
Explanation:

A 4 x 4 square admits exactly 2 safe layouts.

Example 2

Input:
n = 1
Output:
1
Explanation:

One cell, one tower: a single layout.

Example 3

Input:
n = 6
Output:
4
Explanation:

A 6 x 6 square admits 4 safe layouts.

Constraints

  • 1 ≤ n ≤ 11

How this problem is judged

Answers
Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.
Time per case
Python 1,600 msC++ 400 msJava 800 msJavaScript 800 msTypeScript 800 ms

Expected complexity

Time
O(n!)
Space
O(n)

What the author was aiming for. Your own solution is not measured against it.

Asked in an interview

Were you asked this in an interview? Say where, anonymously.

Code
Loading the editor…