LeetCode 51. N 皇后

主页有其他数据结构内容(持续更新中)

难度: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;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值