主页有其他数据结构内容(持续更新中)
难度:Hard
代码:
class Solution {
private:
vector<vector<string>> result;
// n为输入的棋盘大小
// row是当前递归到棋盘的第几行了(从0开始)
void dfs(int n, int row, vector<string>& chessboard) {
if (row == n) {
// 此时说明已经找到了一个可行的方案
result.emplace_back(chessboard);
return;
}
// 遍历列
for (int col = 0; col < n; col++) {
// 验证合法就可以放
if (isValid(row, col, chessboard, n)) {
// 放置皇后
chessboard[row][col] = 'Q';
dfs(n, row + 1, chessboard); // row+1确保当前行放置皇后之后,不会再在当前行放置皇后
// 回溯,撤销皇后
chessboard[row][col] = '.';
}
}
}
bool isValid(int row, int col, vector<string>& chessboard, int n) {
// 检查列
for (int i = 0; i < row; i++) { // 剪枝:只需判断第row行之前的行,因为第row行下面的行还未放置皇后
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) {
vector<string> chessboard(n, string(n, '.'));
dfs(n, 0, chessboard);
return result;
}
};