N-Queens II

The n-queens puzzle is the problem of placing n queens on an n x n chessboard such that no two queens attack each other. Given an integer n, return the number of distinct solutions to the n-queens puzzle.

30:00

N-Queens II
hard
Free written solution
Topics
Companies

The n-queens puzzle is the problem of placing n queens on an n x n chessboard such that no two queens attack each other. Given an integer n, return the number of distinct solutions to the n-queens puzzle.

Example 1:
Input: {"n":4}
Output: 2
Constraints:
  • 1≤n≤91 \leq n \leq 9

Test Cases
Input (Stdin)
Expected Output (Stdout)
Execution Result

Run code to see results.

Input
arr ={"n":4}

Place one queen per row on a 4x4 board. Three sets remember which columns, diagonals (r - c) and anti-diagonals (r + c) are taken.

board, one queen per row

0
1
2
3
0
1
2
3

taken sets

cols

0
1
2
3

diag (r - c)

-3
-2
-1
0
1
2
3

anti (r + c)

0
1
2
3
4
5
6

count

0

Variables
VariableValue
n4
count0
DepthFunction Call
Stack empty
0/79