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

机器人的运动范围

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;
    }
};

全部评论

相关推荐

Skywalker_lgy:这种啥毕还回他干啥,头像都暗示你拉黑了
点赞 评论 收藏
分享
牛客279957775号:铁暗恋
点赞 评论 收藏
分享
躺尸修仙中:因为很多92的也去卷中小厂,反正投递简历不要钱,面试不要钱,时间冲突就推,不冲突就面试积累经验
点赞 评论 收藏
分享
点赞 收藏 评论
分享
牛客网
牛客企业服务