kniost

谁怕,一蓑烟雨任平生

0%

LeetCode 52. N-Queens II

52. N-Queens II

Difficulty:: Hard

The n-queens puzzle is the problem of placing n queens on an n×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
2
3
4
5
6
7
8
9
10
11
12
13
14
Input: 4
Output: 2
Explanation: There are two distinct solutions to the 4-queens puzzle as shown below.
[
[".Q..", // Solution 1
"...Q",
"Q...",
"..Q."],

["..Q.", // Solution 2
"Q...",
"...Q",
".Q.."]
]

Solution

Language: Java

将上一题精简一下

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
class Solution {
int count = 0;
public int totalNQueens(int n) {
if (n <= 0) {
return 0;
}
boolean[][] sets = new boolean[3][n * 2 + 1];
dfsHelper(n, 0, sets);
return count;
}

private void dfsHelper(int n, int index, boolean[][] sets) {
if (index == n) {
count++;
return;
}
for (int i = 0; i < n; i++) {
int left = index - i + n;
int right = index + i;
if (sets[0][i] || sets[1][left] || sets[2][right]) {
continue;
}
sets[0][i] = true;
sets[1][left] = true;
sets[2][right] = true;
dfsHelper(n, index + 1, sets);
sets[0][i] = false;
sets[1][left] = false;
sets[2][right] = false;
}
}
}