All problems

Problem 283

N-Queens Count

Hard · 30 pts · Backtracking, Bit Manipulation

Problem

Place N queens on an N x N chessboard so that no two queens attack each other. A queen attacks every square in its row, its column and both of its diagonals, so no two queens may share a row, a column or a diagonal. Print the number of different valid arrangements. Arrangements that are rotations or reflections of each other count separately. Use backtracking row by row: place one queen per row, trying each column that is not attacked, and keep sets (or bit masks) of the used columns and the two diagonal directions (r + c and r - c).

Input

A single integer N.

Output

Print the number of arrangements.

Constraints

1 <= N <= 12

Example input

4

Example output

2

Explanation

On a 4 x 4 board there are exactly two arrangements: queens in columns 2, 4, 1, 3 (rows 1 to 4) and its mirror image, columns 3, 1, 4, 2. So the answer is 2.

Every problem here can be used in a RelayTrixCode team match. Create a room.

Previous: Eventual Safe States Next: Kth Valid Parentheses String