每日一题之拉低通过率 回溯算法 leetcode 51 N皇后

思路

建立决策树,每个节点的属性:

  1. 路径
  2. 选择列表

遍历决策树的每一个节点即可。每个节点的选择:在该行的任意一列放置一个皇后。

class Solution {
private:
    vector<vector<string>> allPath;
public:
    void backTrack(vector<string>& path, int row) {
        if (path.size() == row) {
            allPath.push_back(path);
            return ;
        }
        for (int i = 0; i < path.size(); i ++) {
            if (!isVaild(row, i, path))   continue;
            path[row][i] = 'Q';
            backTrack(path, row + 1);
            path[row][i] = '.';
        }
    }

    bool isVaild(int row, int col, vector<string>& path) {
        for (int i = row - 1; i >= 0; i --) {           //观察同一列
            if (path[i][col] == 'Q')    return false;
        }
        
        for (int i = row - 1, j = col - 1; i >= 0 && j >= 0; i --, j --) {        //观察左上
            if (path[i][j] == 'Q')  return false;
        }

        for (int i = row - 1, j = col + 1; i >= 0 && j < path.size(); i --, j ++) {       //观察右上
            if (path[i][j] == 'Q')  return false;
        }

        return true;
    }

    vector<vector<string>> solveNQueens(int n) {
        vector<string> path(n, string(n, '.'));
        backTrack(path, 0);
        return allPath;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值