Gallery Ceiling Sensors

HardbacktrackingAlso known as N-Queens II

An art gallery is fitting motion sensors to a ceiling of n × n panels. Each sensor beams along its row, its column and both diagonals to the walls, and two sensors on one beam set each other off. Some panels are glass skylights: nothing mounts on glass, but beams pass through it. The gallery needs exactly n sensors and wants to know how many layouts are possible.

Your task

Write countLayouts(ceiling). ceiling is a list of n strings of length n; ceiling[r][c] is '.' for a normal panel and '#' for a skylight. Return the number of ways to place n sensors on normal panels so that no two share a row, a column or a diagonal.

Two layouts are different if some panel has a sensor in one and not in the other. Skylights do not block beams. If no layout exists, return 0.

countLayouts(ceiling: string[]) → int

Examples

Example 1
Input
ceiling = ["....", "....", "....", "...."]
Output
2
Why

Writing each row's sensor column, the two layouts are 1, 3, 0, 2 and its mirror image 2, 0, 3, 1. Every other try shares a column or diagonal.

Example 2
Input
ceiling = [".#..", "....", "....", "...."]
Output
1
Why

The skylight at row 0, column 1 rules out 1, 3, 0, 2, which needs a sensor there. The mirror 2, 0, 3, 1 survives.

Example 3
Input
ceiling = ["#"]
Output
0
Why

The only panel is a skylight, so no sensor can be placed and the answer is 0.

Constraints

  • 1 ≤ n ≤ 10
  • Every row of ceiling has length n.
  • Each character is '.' or '#'.
Start with brute force

Choosing any n of the n² panels means about 17 trillion choices on a 10 × 10 ceiling. Even one sensor per row and column (every column ordering) is 10! = 3,628,800 full layouts, each checked at the end, though most clash within the first two or three rows.

Hints

0 of 4 shown

Walkthrough and solution

Unlocks when you pass every test. Stuck for a while? Looking is fine too, as long as you then close it and write the code yourself.

Ctrl+Enter runs

Run your code to see results here. Run checks the examples. Submit checks every test, including hidden edge cases.

Write code