-
Notifications
You must be signed in to change notification settings - Fork 0
/
N-Queens II
47 lines (35 loc) · 1.12 KB
/
N-Queens II
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
45
46
47
public class Solution {
public int totalNQueens(int n) {
// IMPORTANT: Please reset any member data you declared, as
// the same Solution instance will be reused for each test case.
//this is the array to store the queen position in each row
int[] path = new int[n];
return solveNQueensHelper(n, n, path);
}
public int solveNQueensHelper(int n, int row, int[] path) {
if (row == 0) {
return 1;
} else {
int sum = 0;
for (int p=0; p<n; p++) {
//in row index, put queue at column p
if (isValid(path, p, row-1, n)) {
path[row-1] = p;
sum+=solveNQueensHelper(n, row-1, path);
}
}//end for
return sum;
}
}
public boolean isValid(int[] path, int queen, int row, int n) {
for (int i=n-1; i>row; i--) {
int col = path[i];
//check if col is duplicated
if (col == queen) return false;
int row_distance = Math.abs(row - i);
int col_distance = Math.abs(col - queen);
if (col_distance == row_distance) return false;
}
return true;
}
}