回溯法
代码语言:javascript复制class Solution {
private:
vector<vector<string>> solution;
vector<string> board;
int size = 0;
public:
bool notValid(int row, int col) {
for (int i = row - 1;i >= 0;i--)
if (board[i][col] == 'Q') return true;
for (int i = row - 1, j = col - 1;i >= 0 && j >= 0;i--, j--)
if (board[i][j] == 'Q') return true;
for (int i = row - 1, j = col 1;i >= 0 && j < size;i--, j )
if (board[i][j] == 'Q') return true;
return false;
}
void backtrack(int row) {
/**1.路径(row);2.选择列表(board-col)**/
if (row == size) {
solution.emplace_back(board);
return;
}
for (int col = 0;col < size;col ) {
if (notValid(row, col)) continue; // 剪枝不合法选择
board[row][col] = 'Q'; // 做选择
backtrack(row 1);
board[row][col] = '.'; // 撤销选择
}
}
vector<vector<string>> solveNQueens(int n) {
size = n;
board = vector<string> (n, string(n, '.'));
backtrack(0);
return solution;
}
};
致谢
感谢「代码随想录」公众号梳理的思路,欢迎大家关注这位大佬的公号