forked from fishercoder1534/Leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
_52.java
44 lines (40 loc) · 1.19 KB
/
_52.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
33
34
35
36
37
38
39
40
41
42
43
44
package com.fishercoder.solutions;
/**
* 52. N-Queens II
*
* Follow up for N-Queens problem.
* Now, instead outputting board configurations, return the total number of distinct solutions.
*/
public class _52 {
public static class Solution1 {
/**credit: https://discuss.leetcode.com/topic/29626/easiest-java-solution-1ms-98-22*/
int count = 0;
public int totalNQueens(int n) {
boolean[] cols = new boolean[n];
boolean[] diagnol = new boolean[2 * n];
boolean[] antiDiagnol = new boolean[2 * n];
backtracking(0, cols, diagnol, antiDiagnol, n);
return count;
}
private void backtracking(int row, boolean[] cols, boolean[] diagnol, boolean[] antiDiagnol,
int n) {
if (row == n) {
count++;
}
for (int col = 0; col < n; col++) {
int x = col - row + n;
int y = col + row;
if (cols[col] || diagnol[x] || antiDiagnol[y]) {
continue;
}
cols[col] = true;
diagnol[x] = true;
antiDiagnol[y] = true;
backtracking(row + 1, cols, diagnol, antiDiagnol, n);
cols[col] = false;
diagnol[x] = false;
antiDiagnol[y] = false;
}
}
}
}