51.N 皇后
题目链接 文章讲解 视频讲解
递归三部曲
- 递归函数参数
需要传入当前chessBoard和棋盘大小n,以及当前要放置皇后的行数rowvoid backtracking(vector<string>& chessBoard, int n, int row);
- 递归终止条件
当最后一个皇后放置好后结束if(row == n) {result.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] = '.'; // 回溯,撤销皇后} }
整体代码如下:
class Solution {
private:vector<vector<string>> result;
public:vector<vector<string>> solveNQueens(int n) {vector<string> chessBoard(n, string(n, '.'));backtracking(chessBoard, n, 0);return result;}void backtracking(vector<string>& chessBoard, int n, int row) {// 终止条件,回收结果if(row == n) {result.push_back(chessBoard);return ;}for(int i = 0; i < n; ++i) {if(isValid(chessBoard, n, row, i)) {chessBoard[row][i] = 'Q';backtracking(chessBoard, n, row + 1);chessBoard[row][i] = '.';}}}bool isValid(vector<string>& chessBoard, int n, int row, int col) {// 检查列for(int i = 0; i < row; ++i) {if(chessBoard[i][col] == 'Q') return false;}// 检查45°角for(int i = row - 1, j = col - 1; i >= 0 && j >= 0; --i, --j) {if(chessBoard[i][j] == 'Q') return false;}// 检查135°角for(int i = row - 1, j = col + 1; i >= 0 && j < n; --i, ++j) {if(chessBoard[i][j] == 'Q') return false;}return true;}
};