51. N-Queens
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:
[ [".Q..", // Solution 1 "...Q", "Q...", "..Q."], ["..Q.", // Solution 2 "Q...", "...Q", ".Q.."] ]
题目大意:n皇后问题,在n * n的棋盘上,摆放n个皇后,是同行同列以及两条同斜边不同时出现两个皇后。列出所有方案。
解题思路:裸dfs摆放皇后位置。
代码如下:
class Solution {
private:
vector<vector<string> > ans;
char a[1000][1000]; //表示棋盘
int vis[10000]; //判断列是否重复
public:
bool ok(int n,int x,int y){ //判断斜边上没有其他皇后(左斜上、左斜下、右斜上、右斜下四个方向遍历)
for(int i = x + 1,j = y + 1;i < n && j < n ; i ++,j++ ){
if(a[i][j] == 'Q')
return false;
}
for(int i = x - 1,j = y - 1;i >= 0 && j >= 0 ;i -- ,j --){
if(a[i][j] == 'Q')
return false;
}
for(int i = x + 1,j = y - 1;i < n && j >=0 ;i ++ ,j --){
if(a[i][j] == 'Q')
return false;
}
for(int i = x - 1,j = y + 1;i >= 0 && j < n;i --,j ++){
if(a[i][j] == 'Q')
return false;
}
return true;
}
void dfs(int n,int x){
if(x == n){ 如果皇后以摆放完,把棋盘数组转换成字符串数组押入答案数组
vector<string> vt;
for(int i = 0;i < n;i ++){
string ns = "";
for(int j = 0;j < n ;j ++){
ns += a[i][j];
}
vt.push_back(ns);
}
ans.push_back(vt);
return ;
}
for(int i = 0;i < n;i ++){
if(vis[i] || !ok(n,x,i))
continue;
a[x][i] = 'Q';
vis[i] = 1;
dfs(n, x + 1);
vis[i] = 0;
a[x][i] = '.';
}
}
vector<vector<string> > solveNQueens(int n) {
for(int i = 0;i < n; i ++){
for(int j = 0;j < n;j ++){
a[i][j] = '.';
}
}
dfs(n,0);
return ans;
}
};