题解 | #机器人的运动范围#

机器人的运动范围

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

class Solution {
public:
    //记录四个方向
    int dir[4][2]={{-1,0},{1,0},{0,-1},{0,1}};
    //记录答案
    int res=0;
    //标记访问格子
    int flag[101][101];
    //计算一个数字的每个数之和
    int cal(int n) {
        int sum=0;
        while(n) {
            sum+=(n%10);
            n/=10;
        }
        return sum;
    }
    void dfs(int i,int j,int threshold,int rows,int cols) {
        //如果行列和数字相加大于threshold
        if(cal(i)+cal(j)>threshold) return;
        //如果越界或者已经访问过
        if(i<0||i>=rows||j<0||j>=cols||flag[i][j]) return;
        res+=1;
        flag[i][j]=1;
        //遍历所有方向
        for(int k=0;k<=3;k++) {
            dfs(i+dir[k][0],j+dir[k][1],threshold,rows,cols);
        }
    }
    int movingCount(int threshold, int rows, int cols) {
        dfs(0,0,threshold,rows,cols);
        return res;
    }
};

全部评论

相关推荐

04-29 22:35
门头沟学院 Java
牛友说改了名字能收到offer:旧图新发查看图片
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务