-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathN-Queens.java
More file actions
executable file
·40 lines (38 loc) · 1.19 KB
/
N-Queens.java
File metadata and controls
executable file
·40 lines (38 loc) · 1.19 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
public class Solution {
public ArrayList<String[]> solveNQueens(int n) {
ArrayList<String[]> res = new ArrayList<String[]>();
solveNQ(n, 0, new int[n], res);
return res;
}
private void solveNQ(int n, int row, int[] queens, ArrayList<String[]> res){
if(row == n){
String[] strs = new String[n];
char[] arr = new char[n];
Arrays.fill(arr, '.');
for(int i = 0; i < n; i++){
arr[queens[i]] = 'Q';
strs[i] = new String(arr);
arr[queens[i]] = '.';
}
res.add(strs);
return;
}
for(int col = 0; col < n; col++){
if(fit(n, queens, row, col)){
queens[row] = col;
solveNQ(n, row + 1, queens, res);
}
}
}
private boolean fit(int n, int[] queens, int row, int col){
int leftTop = col;
int rightTop = col;
for(int i = row - 1; i >= 0; i--){
leftTop--;
rightTop++;
if(queens[i] == col || queens[i] == leftTop || queens[i] == rightTop)
return false;
}
return true;
}
}