-
-
Notifications
You must be signed in to change notification settings - Fork 8.8k
/
Copy pathSolution.java
37 lines (36 loc) · 1.18 KB
/
Solution.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
class Solution {
public List<List<String>> solveNQueens(int n) {
List<List<String>> res = new ArrayList<>();
String[][] g = new String[n][n];
for (int i = 0; i < n; ++i) {
String[] t = new String[n];
Arrays.fill(t, ".");
g[i] = t;
}
boolean[] col = new boolean[n];
boolean[] dg = new boolean[2 * n];
boolean[] udg = new boolean[2 * n];
dfs(0, n, col, dg, udg, g, res);
return res;
}
private void dfs(int u, int n, boolean[] col, boolean[] dg, boolean[] udg, String[][] g,
List<List<String>> res) {
if (u == n) {
List<String> t = new ArrayList<>();
for (String[] e : g) {
t.add(String.join("", e));
}
res.add(t);
return;
}
for (int i = 0; i < n; ++i) {
if (!col[i] && !dg[u + i] && !udg[n - u + i]) {
g[u][i] = "Q";
col[i] = dg[u + i] = udg[n - u + i] = true;
dfs(u + 1, n, col, dg, udg, g, res);
g[u][i] = ".";
col[i] = dg[u + i] = udg[n - u + i] = false;
}
}
}
}