cols.get(i) ==col
判断是否在斜线上,看row和col差或者合是否相等,loop此时cols所有行。row = cols.size(),col是此时dfs的试探点。
i - cols.get(i) == row - col 左上到右下
i + cols.get(i) ==row + col 右上到左下
class Solution {
public List<List<String>> solveNQueens(int n) {
List<List<String>> ret = new ArrayList<>();
if(n < 1){
return ret;
}
List<Integer> cols = new ArrayList<Integer>();
dfs(n, cols, ret);
return ret;
}
List<String> draw(int n, List<Integer> cols){
List<String> ret = new ArrayList<String>();
for(int i = 0; i < n ; i ++){
StringBuilder sb = new StringBuilder();
for(int j = 0; j < n ; j ++){
sb.append(cols.get(i) == j ? "Q" : ".");
}
ret.add(sb.toString());
}
return ret;
}
void dfs(int n, List<Integer> cols, List<List<String>> ret){
if(cols.size() == n){
ret.add(draw(n, cols));
return;
}
for(int i = 0; i < n ; i ++){
//i就是当前col的位置
if(isValid(i,cols)){
cols.add(i);
dfs(n, cols, ret);
cols.remove(cols.size() - 1);
}
}
}
boolean isValid(int col, List<Integer> cols){
int row = cols.size();
for(int i = 0; i < row; i ++){
if(cols.get(i) == col || cols.get(i) - i == col - row || cols.get(i) + i == col + row) {
return false;
}
}
return true;
}
}