-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathNQueens.java
More file actions
38 lines (38 loc) · 1.09 KB
/
NQueens.java
File metadata and controls
38 lines (38 loc) · 1.09 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
public class NQueens {
ArrayList<String[]> ans;
public ArrayList<String[]> solveNQueens(int n) {
ans = new ArrayList<String[]>();
int[] col = new int[n];
solve(0, col, n);
return ans;
}
void solve(int from, int[] col, int n){
if(from == n){
String[] tmp = new String[n];
for(int i = 0; i < n; i++)
tmp[i] = geneQueen(col[i], n);
ans.add(tmp);
}else{
for(int i = 0; i < n; i++){
if(nofight(col, from, i)){
col[from] = i;
solve(from+1, col, n);
}
}
}
}
String geneQueen(int idx, int n){
char[] ans = new char[n];
for(int i = 0; i < n; i++){
if(i == idx) ans[i] = 'Q';
else ans[i] = '.';
}
return new String(ans);
}
boolean nofight(int[] col, int idx, int c){
for(int i = 0; i < idx; i++)
if(col[i] == c || Math.abs(idx -i) == Math.abs(c - col[i]))
return false;
return true;
}
}