forked from algorithm024/algorithm024
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSolveNQueens_51.java
More file actions
76 lines (71 loc) · 2.41 KB
/
Copy pathSolveNQueens_51.java
File metadata and controls
76 lines (71 loc) · 2.41 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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
import java.util.*;
public class SolveNQueens_51 {
// 设置成员变量减少递归调用参数传递
int n;
List<List<String>> res;
// 判断列上是否有皇后
boolean[] col;
// 判断主对角线上是否有皇后
boolean[] main;
// 判断副对角线上是否有皇后
boolean[] sub;
public List<List<String>> solveNQueens(int n) {
res = new ArrayList<>();
if (n == 0) {
return res;
}
this.n = n;
col = new boolean[n];
main = new boolean[n * 2 - 1];
sub = new boolean[n * 2 - 1];
Deque<Integer> path = new ArrayDeque<>();
dfs(0, path);
return res;
}
public void dfs(int row, Deque<Integer> path) {
// row 从第0行开始,如果 row=n 表示已经得到了一个结果
if (row == n) {
res.add(convertToBoard(path));
}
for (int i = 0; i < n; i++) {
// 主对角线行数减列数值固定,副对角线行数加列数值固定
// 这里不能用 row - i 直接判断主对角线,可能会出现负值,使用 row-i+n-1
if (!col[i] && !main[row - i + n - 1] && !sub[row + i]) {
col[i] = true;
main[row - i + n - 1] = true;
sub[row + i] = true;
path.addLast(i);
dfs(row + 1, path);
col[i] = false;
main[row - i + n - 1] = false;
sub[row + i] = false;
path.removeLast();
}
}
}
public List<String> convertToBoard(Deque<Integer> path) {
List<String> res = new ArrayList<>();
Iterator<Integer> iterator = path.iterator();
while(iterator.hasNext()) {
int i = iterator.next();
StringBuilder sb = new StringBuilder();
for (int j = 0; j < n; j++) {
if (j != i) {
sb.append(".");
} else {
sb.append("Q");
}
}
res.add(sb.toString());
}
// // 简化以上写法
// // repeat 为 jdk11 新增方法
// for (Integer num : path) {
// StringBuilder row = new StringBuilder();
// row.append(".".repeat(Math.max(0, n)));
// row.replace(num, num + 1, "Q");
// res.add(row.toString());
// }
return res;
}
}