forked from hongtaocai/code_interview
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathn-queen.java
More file actions
executable file
·57 lines (51 loc) · 1.59 KB
/
n-queen.java
File metadata and controls
executable file
·57 lines (51 loc) · 1.59 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 {
int res[];
boolean colUsed[];
ArrayList<String[]> resarray;
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(!colUsed[i] && check(row,i)){
colUsed[i] = true;
res[row] = i;
if(row==n-1){
String[] ans = new String[n];
for(int i1=0;i1<n;i1++){
StringBuilder sb =new StringBuilder("");
for(int i2=0;i2<n;i2++){
if(i2!=res[i1]){
sb.append(".");
}else{
sb.append("Q");
}
}
ans[i1] = sb.toString();
}
resarray.add(ans);
}else{
solvelayer(n,row+1);
}
colUsed[i] = false;
}
}
}
public ArrayList<String[]> solveNQueens(int n) {
// Start typing your Java solution below
// DO NOT write main() function
if(n==0){
return new ArrayList<String[]>();
}
res = new int[n];
colUsed = new boolean[n];
resarray = new ArrayList<String[]>();
solvelayer(n,0);
return resarray;
}
}