Menu
CoddyTech

N-Queens II

A queen on a chessboard attacks every square in its row, in its column and along both of its diagonals, however far away. You get an integer n. Return the number of ways to place n queens on an n × n board so that no two queens attack each other.

Two ways are different when some square holds a queen in one and is empty in the other. So a board and its mirror image count as two ways, even though they look alike.

Function

totalNQueens(n: integer) → integer
ninteger
the size of the board and the number of queens
Returnsinteger
the number of ways to place the queens so that none attacks another

Constraints

  • 1 ≤ n ≤ 12
  • The answer for n = 12 is 14,200, so it fits in a 32-bit integer.

Examples

Input
n = 4
Output
2
Explanation
Writing the column of each row's queen from top to bottom, the two boards are 1, 3, 0, 2 and 2, 0, 3, 1. Each is the mirror image of the other, and they count as two ways. Every other choice puts two queens on a shared column or diagonal.

lock icon+10 hidden tests on Submit

challenge icon

Follow-up

Can you count only the boards that stay different after rotating and mirroring the board? For n = 8, the 92 boards fall into 12 such groups.

Reset code
def totalNQueens(n):
    # Write code here
Test cases

Case 1

Case 2

Input

n = 4

Expected

2