problems / 104

Peaceful Queens Count

medium backtracking bitmask 3000 ms · 256 MB

Peaceful Queens Count

You are given an n × n chessboard. Some cells are cracked and cannot hold a piece; the rest are sound.

Count the number of ways to place n queens on sound cells so that no two queens attack each other. A queen attacks every other cell in its row, its column, and both of its diagonals, so a valid placement has exactly one queen per row and exactly one queen per column, and no two queens share a diagonal.

The input consists of T independent boards; solve each one.

Input

The first line contains an integer T (1 ≤ T ≤ 40), the number of boards.

Each board is described as follows:

  • A line with one integer n (1 ≤ n ≤ 14), the board size.
  • n lines follow, each a string of exactly n characters over . and #. The character . marks a sound cell and # marks a cracked cell.

Output

For each board, print one line with a single integer: the number of valid placements of n non-attacking queens that avoid every cracked cell.

Notes

In the first example, the board is empty and n = 4; the classic 4-queens puzzle has exactly 2 solutions.

In the second example, the cell in row 1, column 3 is cracked. That cell is used by one of the two 4-queens solutions, so only 1 placement remains.

Example 1

Input

1
4
....
....
....
....

Output

2

Example 2

Input

1
4
..#.
....
....
....

Output

1

Hints · reveal one at a time if you're stuck

Hint 1

Each row needs exactly one queen, so place queens one row at a time with backtracking. With n up to 14 the search tree is small enough, so the real question is how cheaply each candidate column can be checked.

Hint 2

Keep the used columns and both diagonal directions as bitmasks, and store each row's cracked cells as a mask too. The legal columns for the current row are then whatever bits remain after removing the blocked ones, and you can walk those bits directly. Do not rely on mirror symmetry, since cracked cells break it.

report an issue Prefer your own editor? sooks prep 104 (CLI)
Sign in to run code

Run your code on the examples, or submit it against every test.