Error message here!

Hide Error message here!

Error message here!

Hide Error message here!

Error message here!

Close

## LeetCode 51. N-QueensN皇后 (C++)(八皇后问题)

silentteller 2019-07-11 20:07:00 阅读数:75 评论数:0 点赞数:0 收藏数:0

## 题目：

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.

Example:

```Input: 4
Output: [
[".Q..",  // Solution 1
"...Q",
"Q...",
"..Q."],

["..Q.",  // Solution 2
"Q...",
"...Q",
".Q.."]
]
Explanation: There exist two distinct solutions to the 4-queens puzzle as shown above.```

## 分析：

[x,y]位置对应从左下角至右上角的对角线diag1[x+y]，而对应从左上角至右下角的对角线diag2[y-x+n-1]，这样每一个位置能否放置皇后判断的条件都有了，不用再使用一个棋盘大小的二维数组来标识了。

## 程序：

```class Solution {
public:
void update(int n, vector<vector<int>> &vec, int x, int y){
for(int i = ; i < n; ++i){
vec[i][y] = ;
vec[x][i] = ;
}
int i = ,j = ;
for(i = x, j = y; i < n && j < n; ++i, ++j){
vec[i][j] = ;
}
for(i = x, j = y; i >=  && j >= ; --i, --j){
vec[i][j] = ;
}
for(i = x, j = y; i < n && j >= ; ++i, --j){
vec[i][j] = ;
}
for(i = x, j = y; i >=  && j < n; --i, ++j){
vec[i][j] = ;
}
return;
}
void queen(int n, int y, vector<string> &temp_res, vector<vector<int>> &sta){
if(y == n){
res.push_back(temp_res);
return;
}
for(int j = ; j < n; ++j){
if(sta[y][j] == ){
vector<string> temp2 = temp_res;
temp_res[y][j] = 'Q';
vector<vector<int>> temp = sta;
update(n, sta, y, j);
queen(n, y+, temp_res, sta);
sta = temp;
temp_res = temp2;
}
else
continue;
}
return;
}
vector<vector<string>> solveNQueens(int n) {
vector<string> temp_res(n, string(n, '.'));
vector<vector<int>> sta(n, vector<int>(n,));
queen(n, , temp_res, sta);
return res;
}
private:
vector<vector<string>> res;
};```
```class Solution {
public:
void queen(int n, int x, vector<string> &temp_res){
if(x == n){
res.push_back(temp_res);
return;
}
for(int y = ; y < n; ++y){
if(col[y] ==  && diag1[x+y] ==  && diag2[y-x+n-] == ){
temp_res[x][y] = 'Q';
col[y] = ;
diag1[x+y] = ;
diag2[y-x+n-] = ;
queen(n, x+, temp_res);
temp_res[x][y] = '.';
col[y] = ;
diag1[x+y] = ;
diag2[y-x+n-] = ;
}
else
continue;
}
return;
}
vector<vector<string>> solveNQueens(int n) {
vector<string> temp_res(n, string(n, '.'));
col = vector<int>(n, );
diag1 = vector<int>( * n - , );
diag2 = vector<int>( * n - , );
queen(n, , temp_res);
return res;
}
private:
vector<vector<string>> res;
vector<int> col;
vector<int> diag1;
vector<int> diag2;
};```

https://www.cnblogs.com/silentteller/p/11172352.html