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

机器人的运动范围

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

  public:
    int movingCount(int threshold, int rows, int cols) {
        if (rows <= 0 || cols <= 0 || threshold < 0)
            return 0;
        vector<vector<int>>matrix(rows, vector<int>(cols, 0));
        return dfs(matrix, threshold, rows, cols, 0, 0);
    }
    int dfs(vector<vector<int>>&matrix, int threshold, int rows, int cols, int x,
            int y) {
        if (!(valid(threshold,  x,  y,  rows,  cols))) return 0;
        if (matrix[x][y] != 0) return 0;
        matrix[x][y] = 1;
        return 1 + dfs(matrix, threshold, rows, cols, x + 1, y) +
               dfs(matrix, threshold, rows, cols, x - 1, y) +
               dfs(matrix, threshold, rows, cols, x, y + 1) +
               dfs(matrix, threshold, rows, cols, x, y - 1);
    }
    bool valid(int threshold, int x, int y, int rows, int cols) {
        if (x < 0 || x >= rows || y < 0 || y >= cols) {
            return false;
        }
        
        if (cal(x)+cal(y) > threshold) {
            return false;
        }
        return true;
    }
    int cal(int num){
        int sum=0;
        while(num){
            sum+=num%10;
            num=num/10;
        }
        return sum;
    }
};
全部评论

相关推荐

码农索隆:单休一个月少休息4天,一年就是48天,平时节假日,别人3天假期,单休的两天
点赞 评论 收藏
分享
06-15 18:44
黄淮学院 Java
Lynn012:如果是居民楼还是算了吧,看着有点野呢
点赞 评论 收藏
分享
找到实习了&nbsp;给了150一天&nbsp;但是说是低代码&nbsp;值得去吗
码农索隆:是在没实习,可去,待个一两周,不行就润呗
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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