LeetCode51 N 皇后
前言
题目: 51. N 皇后
文档: 代码随想录——N 皇后
编程语言: C++
解题状态: 投降投降…
思路
回溯法,思路其实不算难,就是判断棋子的位置是否合法有难度。
代码
class Solution {
private:
vector<vector<string>> res;
void backtracking(int n, int row, vector<string>& chessboard) {
if (row == n) {
res.push_back(chessboard);
return;
}
for (int col = 0; col < n; col++) {
if (isValid(row, col, chessboard, n)) {
chessboard[row][col] = 'Q';
backtracking(n, row + 1, chessboard);
chessboard[row][col] = '.';
}
}
}
bool isValid(int row, int col, vector<string>& chessboard, int n) {
for (int i = 0; i < row; i++) {
if (chessboard[i][col] == 'Q') {
return false;
}
}
for (int i = row - 1, j = col - 1; i >= 0 && j >= 0; i--, j--) {
if (chessboard[i][j] == 'Q') {
return false;
}
}
for (int i = row - 1, j = col + 1; i >= 0 && j < n; i--, j++) {
if (chessboard[i][j] == 'Q') {
return false;
}
}
return true;
}
public:
vector<vector<string>> solveNQueens(int n) {
res.clear();
vector<string> chessboard(n, string(n, '.'));
backtracking(n, 0, chessboard);
return res;
}
};
- 时间复杂度: O ( n ! ) O(n!) O(n!)
- 空间复杂度: O ( n ) O(n) O(n)