class Solution {
private static List<List<String>> rs;//结果集
public List<List<String>> solveNQueens(int n) {
int[] queens=new int[n];
rs=new ArrayList<>();
Arrays.fill(queens,-1);
Set<Integer> columns = new HashSet<Integer>(); //第几列,不能在同一列,row表示行
Set<Integer> diagonals1 = new HashSet<Integer>();
Set<Integer> diagonals2 = new HashSet<Integer>();
Dfs(queens,n,0,columns,diagonals1,diagonals2);
return rs;
}
//回溯的过程
private void Dfs(int[] queens,int n,int row,Set<Integer> columns,Set<Integer> diagonals1,Set<Integer> diagonals2) {
if (row==n){ //回溯结束的条件
List<String> s=generateBoard(queens,n);
rs.add(s);
}
for (int i=0;i<n;i++){
if (columns.contains(i)){
continue;
}
int left=row+i; //row表示行,i表示列
if (diagonals1.contains(left)){
continue;
}
int right=row-i;
if (diagonals2.contains(right)){
continue;
}
queens[row]=i; //记录第row行的第几列可以防止皇后
columns.add(i);
diagonals1.add(left);
diagonals2.add(right);
Dfs(queens,n,row+1,columns,diagonals1,diagonals2);
queens[row]=-1;
columns.remove(i);
diagonals1.remove(left);
diagonals2.remove(right);
}
}
//这个方法是是将棋盘的布局用一个list[String]给表示出来
public List<String> generateBoard(int[] queens, int n){
List<String> board=new ArrayList<>();
for (int i=0;i<n;i++){
char[] row=new char[n];
Arrays.fill(row,'.');
row[queens[i]]='Q';
board.add(new String(row));
}
return board;
}
}
N皇后问题(回溯)
最新推荐文章于 2022-06-11 15:59:30 发布
![](https://img-home.csdnimg.cn/images/20240711042549.png)