13:机器人的运动范围

有一个m行n列的方格,一个机器人从坐标(0 ,0) 的格子开始移动,它每次可以向上下左右移动一格,但不能进入坐标位数和大于threshold的格子,求机器人一共能到达多少个格子

机器人从(0, 0)开始移动,当要移动到(i, j) 时,先判断i, j是否满足条件,如果满足,就进入,递归执行。如果不满足,尝试其他相邻的格子。 需要一个辅助数组visited[][] 来记录移动的踪迹

public static int movingCount(int threshold, int rows, int cols) {
    if (rows < 0 || cols < 0 || threshold < 0) return 0;

    boolean[][] visited = new boolean[rows][cols];
    int count = movingCountCore(threshold, 0, 0, rows, cols, visited);

    return count;
}

public static int movingCountCore(int threshold, int row, int col, int rows, int cols, boolean[][] visited) {
    if (row >= 0 && row < rows && col >= 0 && col < cols &&
        getDigitSum(row) + getDigitSum(col) <= threshold &&
        !visited[row][col]
       ) {
        visited[row][col] = true;
        return 1 + movingCountCore(threshold, row - 1, col, rows, cols, visited) +
            movingCountCore(threshold, row + 1, col, rows, cols, visited) +
            movingCountCore(threshold, row, col - 1, rows, cols, visited) +
            movingCountCore(threshold, row, col + 1, rows, cols, visited);
    }

    return 0;
}

public static int getDigitSum(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、付费专栏及课程。

余额充值