# 【LeetCode】51. N-Queens 解题报告（C++）

900 篇文章 155 订阅
1033 篇文章 56 订阅

id： fuxuemingzhu

## 题目描述

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.


## 解题方法

### 回溯法

python代码如下：

class Solution {
public:
vector<vector<string>> solveNQueens(int n) {
vector<int> board(n, -1);
vector<vector<string>> res;
helper(board, res, 0);
return res;
}
// how to put in row? (havent put down yet)
void helper(vector<int>& board, vector<vector<string>>& res, int row) {
const int N = board.size();
if (row == N) {
vector<string> path(N, string(N, '.'));
for (int i = 0; i < N; i++) {
path[i][board[i]] = 'Q';
}
res.push_back(path);
} else {
for (int col = 0; col < N; col++) {
board[row] = col;
if (isValid(board, row, col)) {
helper(board, res, row + 1);
}
board[row] = -1;
}
}
}
// have put down in (row, col), alright?
bool isValid(vector<int>& board, int row, int col) {
for (int prow = 0; prow < row; prow ++) {
int pcol = board[prow];
if (pcol == col || abs(prow - row) == abs(pcol - col)) {
return false;
}
}
return true;
}
};


## 日期

2018 年 12 月 23 日 —— 周赛成绩新高

• 1
点赞
• 0
收藏
• 打赏
• 0
评论
01-08 373
02-16 135
03-07 2538
12-28 2707
11-06 47
02-14 294
11-16 306
08-05 123
07-09 180
09-09 972
03-07 151
02-01 145
04-10 1040
04-21 344
04-29 1583
05-06 384

### “相关推荐”对你有帮助么？

• 非常没帮助
• 没帮助
• 一般
• 有帮助
• 非常有帮助

¥2 ¥4 ¥6 ¥10 ¥20

1.余额是钱包充值的虚拟货币，按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载，可以购买VIP、C币套餐、付费专栏及课程。