思路 回溯法
找每一行index中 棋子应该放在的列号(i)
所以应该设几个标号
-
因为是一行一行摆放,因此这些 “皇后” 一定不在同一行,无需额外设置状态;
-
为了保证不再同一列, 设 col [ ] 数组设置标志位,如果占了就true
-
为了保证至少两个皇后不同时出现在主对角线或者副对角线,我们的策略是,只要 “检测” 到新摆放的 “皇后” 与已经摆放好的 “皇后” 冲突,就尝试摆放下一个位置,在 “无处安放” 的时候 “剪枝” 。
下面我们研究一下主对角线或者副对角线上的元素有什么特性。我们此时能掌握的信息只有行和列的索引,不妨将它标注在棋盘上。
-
如何输出正确的格式, 记住 row里存的是每一行的棋子的纵坐标,所以我们可以新建一个函数,然后两个for for循环,如果j等于row函数对应的i 则是棋子,否则不是,然后将字符串拼接,我们使用 stringbuilder ,这样一个答案就成了。
class Solution {
public List<List<String>> solveNQueens(int n) {
List<List<String>> res=new ArrayList<>();
if(n<=0) return res;
boolean[] col=new boolean[n];
boolean[] dia1=new boolean[2*n-1];
boolean[] dia2=new boolean[2*n-1];
helper(n, 0, new ArrayList<>(),res, col, dia1, dia2);
return res;
}
//尝试在一个n皇后问题中,摆放第index行的皇后位置
public void helper(int n, int index, List<Integer> row, List<List<String>> res, boolean[] col, boolean[] dia1,boolean[] dia2){
if(index==n){
res.add( generateBoard(n,row));
return ;
}
for(int i=0;i<n;i++){
//尝试将第index行的皇后摆放在第i列
if( !col[i] && !dia1[index+i] && !dia2[index-i+n-1]){
row.add(i);
col[i]=true;
dia1[index+i]=true;
dia2[index-i+n-1]=true;
helper(n, index+1,row, res,col, dia1, dia2);
col[i]=false;
dia1[index+i]=false;
dia2[index-i+n-1]=false;
row.remove(row.size()-1);
}
}
return;
}
public List<String> generateBoard(int n, List<Integer> row){
List<String> list=new ArrayList<>();
for(int i=0;i<n;i++){
StringBuilder str=new StringBuilder();
for(int j=0;j<n;j++){
if(j==row.get(i))
str.append("Q");
else
str.append(".");
}
list.add(str.toString());
}
return list;
}
}