forked from yuduozhou/LeetCode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathNQueen.java
58 lines (55 loc) · 1.61 KB
/
NQueen.java
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
58
public class Solution {
public ArrayList<String[]> solveNQueens(int n) {
// Start typing your Java solution below
// DO NOT write main() function
ArrayList<String[]> ret = new ArrayList<String[]>();
if (n <= 0) {
return ret;
}
int[] sol = new int[n]; //the i-th element is the column number of the queen in the i-th row
placeQueen(sol, 0, ret);
return ret;
}
public void placeQueen(int[] sol, int row, ArrayList<String[]> ret) {
int n = sol.length;
if (row == n) {
ret.add(transform(sol));
return;
}
for (int i = 0; i < n; i++) {
if (check(sol, row, i)) {
sol[row] = i;
placeQueen(sol, row + 1, ret);
}
}
}
public boolean check(int[] sol, int row, int col) {
//check col and diag
for (int i = 0; i < row; i++) {
if (sol[i] == col) {
return false;
}
if (row-i == Math.abs(col-sol[i])) {
return false;
}
}
return true;
}
public String[] transform(int[] sol){
int n = sol.length;
String[] ret = new String[n];
for (int i = 0; i < n; i++) {
StringBuilder sb = new StringBuilder();
for (int j = 0; j < n; j++) {
if (j == sol[i]) {
sb.append("Q");
}
else {
sb.append(".");
}
}
ret[i] = sb.toString();
}
return ret;
}
}