code
class Solution {
List<List<String>> result = new ArrayList();
Stack<String> path = new Stack();
String[][] b;
int n;
boolean[] col;
boolean[] ne;
boolean[] nw;
public List<List<String>> solveNQueens(int _n) {
n = _n;
col = new boolean[n];
ne = new boolean[2*n];
nw = new boolean[2*n];
// 初始化棋盘
b = new String[n][n];
for(int i = 0; i < n; i++){
for(int j = 0; j < n; j++){
b[i][j] = ".";
}
}
dfs(0);
return result;
}
public void dfs(int depth){
if(depth == n){
path.clear();
for(int i = 0; i < n; i++){
StringBuilder sb = new StringBuilder();
for(int j = 0; j < n; j++){
sb.append(b[i][j]);
}
path.push(sb.toString());
}
result.add(new ArrayList(path));
return;
}
for(int i = 0; i < n; i++){
if(!col[i] && !ne[i-depth+n] && !nw[i+depth]){
col[i] = ne[i-depth+n] = nw[i+depth] = true;
b[depth][i] = "Q";
dfs(depth+1);
b[depth][i] = ".";
col[i] = ne[i-depth+n] = nw[i+depth] = false;
}
}
}
}
视频讲解中的最核心的思路