JZ66-机器人的运动范围

机器人的运动范围

https://www.nowcoder.com/practice/6e5207314b5241fb83f2329e89fdecc8?tpId=13&tags=&title=&diffculty=0&judgeStatus=0&rp=1&tab=answerKey

class Solution {
    public int movingCount(int threshold, int rows, int cols) {
        if (rows <= 0 || cols <= 0 || threshold < 0) {
            return 0;
        }
        boolean[][] isVisited = new boolean[rows][cols];
        int count = movingCountCore(threshold, rows, cols, 0, 0, isVisited);
        return count;
    }

    private int movingCountCore(int threshold, int rows, int cols,
                                int row, int col, boolean[][] isVisited) {
        if (row < 0 || col < 0 || row >= rows || col >= cols
                || isVisited[row][col] || sum(row) + sum(col) > threshold) {
            return 0;
        }
        isVisited[row][col] = true;
        return 1 + movingCountCore(threshold, rows, cols, row + 1, col, isVisited)
                + movingCountCore(threshold, rows, cols, row - 1, col, isVisited)
                + movingCountCore(threshold, rows, cols, row, col + 1, isVisited)
                + movingCountCore(threshold, rows, cols, row, col - 1, isVisited);
    }

    private int sum(int num) {
        int temp = 0;
        while (num > 0) {
            temp += num % 10;
            num /= 10;
        }
        return temp;
    }
}

全部评论

相关推荐

头像
05-16 11:16
已编辑
东华理工大学 Java
牛客737698141号:盲猜几十人小公司,庙小妖风大,咋不叫她去4️⃣呢😁
点赞 评论 收藏
分享
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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