The n-queens puzzle is the problem of placing n queens on an n×n chessboard such that no two queens attack each other.
Given an integer n, return all distinct solutions to the n-queens puzzle.
Each solution contains a distinct board configuration of the n-queens' placement, where 'Q' and '.' both indicate a queen and an empty space respectively.
For example,
There exist two distinct solutions to the 4-queens puzzle:
Each solution contains a distinct board configuration of the n-queens' placement, where 'Q' and '.' both indicate a queen and an empty space respectively.
For example,
There exist two distinct solutions to the 4-queens puzzle:
[
[".Q..", // Solution 1
"...Q",
"Q...",
"..Q."],
["..Q.", // Solution 2
"Q...",
"...Q",
".Q.."]
]
题目大意:
找出n皇后的所有方案,
把n个皇后放在n*n的棋盘上,使得它们彼此之间不能攻击(在各自的行,列,斜边上不存在其他皇后)
解题思路:
这里使用了dfs+剪枝,dfs回溯各种可能的位置,剪枝时考虑已占的行,斜边。
AC代码如下:
class Solution {
List<List<String>> rqs=new ArrayList<>();
boolean qflag[][]=new boolean[100][100]; //棋盘数组
boolean row[]=new boolean[100]; //行
boolean bevel1[]=new boolean[200]; //正斜边记录数组
boolean bevel2[]=new boolean[300]; //反斜边记录数组
/**
* @param n 皇后数
* @param index 当前列号
*/
public void dfs(int n,int index){
if(index>=n){ //记录方案
List<String> list=new ArrayList<>();
for (int i = 0; i <n ; i++) {
StringBuffer b=new StringBuffer();
for (int j = 0; j < n; j++) {
if(qflag[i][j]){
b.append("Q");
}else{
b.append(".");
}
}
list.add(b.toString());
}
rqs.add(list);
return ;
}
for (int i = 0; i <n ; i++) {
//剪枝,检查行数组以及两个斜边数组
if(!row[i]&&!bevel1[index-i+n-1]&&!bevel2[index+i]){
row[i]=true;
bevel1[index-i+n-1]=true;
bevel2[index+i]=true;
qflag[i][index]=true;
dfs(n,index+1);
qflag[i][index]=false;
row[i]=false;
bevel1[index-i+n-1]=false;
bevel2[index+i]=false;
}
}
}
public List<List<String>> solveNQueens(int n) {
rqs.clear();
dfs(n,0);
return rqs;
}
}