13.机器人的运动范围

13.机器人的运动范围

题目和代码来自书上

以下是牛客网上ac过的代码

class Solution {
public:
    int movingCount(int threshold, int rows, int cols)
    {
        if (threshold < 0 || rows <= 0 || cols <= 0) return 0;
        vector<vector<bool>> visited;
        for (int i = 0; i < rows; i++ ) {
            vector<bool> tmp_rows(cols,false);
            visited.push_back(tmp_rows);
        }

        int ret = movingCountCore(threshold, rows, cols,0,0, visited);
        return ret;
    }

    int movingCountCore(int threshold, int rows, int cols, int i, int j, vector<vector<bool>>& visited ) {
        int count = 0;
        if (check(threshold, i,j, rows, cols,visited)) {
            visited[i][j] = true;
            count = 1 + movingCountCore(threshold, rows, cols, i+1, j, visited)
                + movingCountCore(threshold, rows, cols, i-1, j, visited)
                + movingCountCore(threshold, rows, cols, i, j+1, visited)
                + movingCountCore(threshold, rows, cols, i, j-1, visited);
        }
        return count;
    }
    int check(int threshold, int i, int j, int rows, int cols, vector<vector<bool>>& visited) {
        if (i >= 0 && i < rows
           && j >= 0 && j < cols
           && !visited[i][j]
           && get_num(i) + get_num(j) <= threshold) {
            return true;
        }
        return false;
    }
    int get_num(int num) {
        int sum = 0;
        while(num>0) {
            sum += num % 10;
            num /= 10;
        }
        return sum;
    }
};

最近比较忙,练的题目比较少,要加油啊!!
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值