51. N-Queens N 皇后

@TOC

# 题目描述

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 日 —— 周赛成绩新高