forked from hongtaocai/code_interview
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathnqueens2.java
More file actions
executable file
·57 lines (52 loc) · 1.33 KB
/
nqueens2.java
File metadata and controls
executable file
·57 lines (52 loc) · 1.33 KB
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
48
49
50
51
52
53
54
55
56
57
public class Solution {
public int totalNQueens(int n) {
// Start typing your Java solution below
// DO NOT write main() function
if(n==0){
return 0;
}
res = new int[n];
colUsed = new boolean[n];
resnum = 0;
solvelayer(n,0);
return resnum;
}
int res[];
int resnum;
boolean colUsed[];
int resnum1;
int resnum2;
public boolean check(int row,int col){
for(int i=0;i<row;i++){
if(Math.abs(row-i)==Math.abs(col-res[i])){
return false;
}
}
return true;
}
public void solvelayer(int n, int row){
for(int i=0;i<n;i++){
if(row==0){
if(n%2==1){
if(i==n/2){
}
}else{
if(i==n/2){
resnum = resnum*2;
return;
}
}
}
if(!colUsed[i] && check(row,i)){
colUsed[i] = true;
res[row] = i;
if(row==n-1){
resnum ++;
}else{
solvelayer(n,row+1);
}
colUsed[i] = false;
}
}
}
}