剑指offer-回溯

1.矩阵中的路径

class Solution {
    int dx[4] = {0, -1, 0, 1}, dy[4] = {1, 0, -1, 0};
    bool dfs(vector<vector<char>>& matrix, int x, int y, string& word, int idx) {
        if (matrix[x][y] != word[idx]) return false;
        if (idx == word.size() - 1) return true;
        char ch = matrix[x][y];
        matrix[x][y] = '*';
        for (int i = 0; i < 4; ++i) {
            int nx = x + dx[i], ny = y + dy[i];
            if (nx >= 0 and nx < matrix.size() and ny >= 0 and ny < matrix[0].size()) {
                if (dfs(matrix, nx, ny, word, idx + 1)) {
                    return true;
                }
            }
        }
        matrix[x][y] = ch;
        return false;
    }
public:
    bool hasPath(vector<vector<char> >& matrix, string word) {
        int m = matrix.size();
        if (m == 0) return false;
        int n = matrix[0].size();
        vector<vector<int>> st(m, vector<int>(n, false));
        for (int i = 0; i < m; ++i) {
            for (int j = 0;j < n; ++j) {
                if (dfs(matrix, i, j, word, 0))
                    return true;
            }
        }
        return false;
    }
};

2.机器人的运动范围

class Solution {
    int pointToSum(int x, int y) {
        int res = 0;
        while (x) { res += x % 10; x /= 10;}
        while (y) { res += y % 10; y /= 10;}
        return res;
    }
public:
    int movingCount(int threshold, int rows, int cols) {
        if (!rows or !cols) return 0;
        int res = 0;
        vector<vector<bool>> st(rows, vector<bool>(cols, false));
        int dx[4] = {0, -1, 0, 1}, dy[4] = {1, 0, -1, 0};
        
        queue<pair<int, int>> q;
        q.push({0, 0});
        while (q.size()) {
            auto [x, y] = q.front(); q.pop();
            if (pointToSum(x, y) > threshold or st[x][y]) continue;
            res++;
            st[x][y] = true;
            for (int i = 0; i < 4; ++i) {
                int nx = x + dx[i], ny = y + dy[i];
                if (nx >= 0 and nx < rows and ny >= 0 and ny < cols) {
                    q.emplace(nx, ny);
                }
            }
        }
        return res;
    }
};
全部评论

相关推荐

Twilight_mu:经典我朋友XXXX起手,这是那种经典的不知道目前行情搁那儿胡编乱造瞎指导的中年人,不用理这种**
点赞 评论 收藏
分享
缓解焦虑的最好方法是回家。鼠鼠昨天上午考完了本科阶段的最后一场考试,大概率考得稀烂,但是没多想,考完立马收拾行李,坐上了提前约好的顺风车飞奔回家。虽然家和学校很近,只有一百多公里的路程,但距离上次回家也已经有三四个月了。每次想回家,期间总有考试、毕业设计、面试、实习等等各种各样的原因,没办法回去,待在学校和公司的每一天也都充斥着无形的压力和焦虑。现在终于完成了答辩,考完了试,公司那边也请了假,是时候回去一趟了。没有提前通知爸妈,想给他们一个惊喜。下午提前到了家,他俩还在上班,只好让外公外婆来给我开门。因为我的回家,晚上外婆在厨房格外忙碌,做了满满一大桌子菜,填饱了我天天吃外卖的肚子。晚上也没空...
梦想是成为七海千秋:取决于家庭吧?其实回家更焦虑了,每天起床父母都问实习找好了没简历投递了没今天有没有面试,但是又没有什么结果,玩两下手机父母就会说你看你啥也没找到为什么天天就知道刷手机,怎么不去学习…我现在就希望我能永远在外面实习,报喜不报忧,等拿到一个好offer再回家
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务