Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Appearance settings

Latest commit

 

History

History
History
54 lines (50 loc) · 1.75 KB

File metadata and controls

54 lines (50 loc) · 1.75 KB
Copy raw file
Download raw file
Open symbols panel
Edit and raw actions
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
package leetcode._51_;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
class Solution {
public List<List<String>> solveNQueens(int n) {
List<List<String>> result = new ArrayList<>();
if (n <= 0) {
return result;
}
LinkedList<Integer> column = new LinkedList<>();
LinkedList<Integer> pie = new LinkedList<>();
LinkedList<Integer> na = new LinkedList<>();
this.DFS(column, pie, na,
0, n, result, new ArrayList<>());
return result;
}
private void DFS(LinkedList<Integer> column, LinkedList<Integer> pie, LinkedList<Integer> na,
int row, int n, List<List<String>> result, List<String> currStat) {
if (row >= n) {
result.add(currStat);
return;
}
for (int i = 0; i < n; i++) {
if (column.contains(i) || pie.contains(i + row) || na.contains(row - i)) {
continue;
}
// 记录皇后可以攻击的点
column.add(i);
pie.add(i + row);
na.add(row - i);
StringBuilder stringBuilder = new StringBuilder();
for (int j = 0; j < n; j++) {
if (j == i) {
stringBuilder.append("Q");
} else {
stringBuilder.append(".");
}
}
this.DFS(column, pie, na, row + 1, n, result, new ArrayList<String>(currStat) {{
add(stringBuilder.toString());
}});
// 移除,便于下一次回溯
column.pollLast();
pie.pollLast();
na.pollLast();
// currStat.remove(stringBuilder.toString());
}
}
}
Morty Proxy This is a proxified and sanitized view of the page, visit original site.