1777. Queens Around Rubble
A chess composer is laying out an n x n board that has been damaged by an earthquake. The grid board contains '.' for a usable square and '#' for a square covered in rubble. A queen cannot be placed on a rubble square, but rubble does not block anything: queens still attack along entire rows, columns and diagonals, passing over rubble.
Return the number of ways to place n queens, one per row and column, on usable squares so that no two queens attack each other. Two placements are different when some queen stands on a different square; the answer is 0 when no placement exists. Solve it row by row with backtracking, keeping bitmasks of occupied columns and both diagonal directions, and AND them with a precomputed mask of allowed squares for the current row. The worst case is about O(n!) time with O(n) extra space, which is fine for n up to 10.
Example 1
- Input:
- board = [[".",".",".","."],[".",".",".","."],[".",".",".","."],[".",".",".","."]]
- Output:
- 2
- Explanation:
With no rubble, the 4 x 4 board has exactly 2 non-attacking placements.
Example 2
- Input:
- board = [["."]]
- Output:
- 1
- Explanation:
A single usable square holds the single queen.
Example 3
- Input:
- board = [[".","#",".","."],[".",".",".","#"],[".",".",".","."],[".",".",".","."]]
- Output:
- 1
- Explanation:
Rubble at two squares removes some of the placements, leaving 1.
Constraints
1 ≤ n ≤ 10; board is an n x n grid of '.' and '#'.
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 4,000 msC++ 1,000 msJava 2,000 msJavaScript 2,000 msTypeScript 2,000 ms
Expected complexity
- Time
- O(n!)
- Space
- O(n)