题解 | 机器人的运动范围

机器人的运动范围

https://www.nowcoder.com/practice/6e5207314b5241fb83f2329e89fdecc8

#include <vector>
class Solution {
public:

    int getSum(int r, int c){
        int ans = 0;
        while(r){
            ans += r%10;
            r /= 10;
        }
        while(c){
            ans += c%10;
            c /=10;
        }
        return ans;
    }
    void dfs(int threshold, int rows, int cols, int r, int c, vector<vector<bool>>& isD){
        if(r<0||r>=rows||c<0||c>=cols||isD[r][c]||getSum(r, c)>threshold) return;
        isD[r][c] = true;
        int a[] = {1, 0, -1, 0, 0, 1, 0, -1};//一个常见做法来简化搜索方向改变的代码
        for(int i = 0; i < 4; ++i){
            dfs(threshold, rows, cols, r+a[i*2], c+a[i*2+1], isD);
        }
    }
    int movingCount(int threshold, int rows, int cols) {
        //最好不要有全局变量
        if(threshold<0)//不只是字符串需要处理负数和0的情况,但是算法题总是不需要特殊处理就能过
            return -1;
        vector<vector<bool> > isD(rows, vector<bool> (cols, false));
        dfs(threshold, rows, cols, 0, 0, isD);
        int cnt = 0;
		//如果之前有传参让dfs自己加就可以不用遍历了,但是晚上我没有思考这样传会不会在递归的过程中产生问题,有兴趣的读者可以自己想想
        for(int i = 0; i < rows; ++i)
            for(int j = 0; j < cols; ++j)
                if(isD[i][j]) ++cnt;
        return cnt;
        
    }
};

dfs,要注意的点基本上已经标注出来了。时间复杂度是O(m*n*(logm+logn)),空间复杂度是O(m*n)。

全部评论

相关推荐

05-25 10:45
门头沟学院 Java
Frank_zhan...:没实习一个项目肯定不够,可以再做一个轮子,技术栈再补一个mq,微服务,整体再换个简历模板,暑期尽量再找一个日常实习
无实习如何秋招上岸
点赞 评论 收藏
分享
不愿透露姓名的神秘牛友
07-01 11:27
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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