文章目录
机器人的运动范围
描述
地上有一个 rows 行和 cols 列的方格。坐标从 [0,0] 到 [rows-1,cols-1] 。一个机器人从坐标 [0,0] 的格子开始移动,每一次只能向左,右,上,下四个方向移动一格,但是不能进入行坐标和列坐标的数位之和大于 threshold 的格子。 例如,当 threshold 为 18 时,机器人能够进入方格 [35,37] ,因为 3+5+3+7 = 18。但是,它不能进入方格 [35,38] ,因为 3+5+3+8 = 19 。请问该机器人能够达到多少个格子?
数据范围: 0 ≤ t h r e s h o l d ≤ 15 0≤threshold≤15 0≤threshold≤15 ,$1≤rows,cols≤100 $
进阶:空间复杂度 O ( n m ) O(nm) O(nm) ,时间复杂度 $O(nm) $
示例1
输入:
1,2,3
返回值:
3
示例2
输入:
0,1,3
返回值:
1
示例3
输入:
10,1,100
返回值:
29
说明:
示例4
输入:
5,10,10
返回值:
21
思路
最容易想到的方法肯定就是遍历,对二维数组的每一位进行遍历,但需要考虑当数组下标不是一位数时需要取出每一位进行相加
public int movingCount(int threshold, int rows, int cols) {
    int count = 0;
    for (int i = 0; i < rows; i++) {
        for (int j = 0; j < cols; j++) {
            int sum = 0;
            if (i > 10) {
                while (i > 0) {
                    sum += i % 10;
                    i /= 10;
                }
            } else {
                sum += i;
            }
            if (j > 10) {
                while (j > 0) {
                    sum += j % 10;
                    j /= 10;
                }
            } else {
                sum += j;
            }
            if (sum <= threshold) {
                count++;
            }
        }
    }
    return count;
}
但这种情况下对于较大规模的数据容易超时
下面使用递归来解决这个问题
- 首先需要定义一个数组access用于记录当前元素是否已经访问过
- 从左上角元素开始递归
- 每次递归先判断是否达到边界条件 
  - 超过矩阵边界直接返回
- 横纵坐标数位之和大于threshold直接返回
- 当前节点已访问直接返回
 
- 如果未访问过当前节点,则结果加一,并表姐当前节点为已访问
- 接着递归当前节点的四个邻居节点,直到递归结束
完整代码
import java.util.*;
public class Solution {
    boolean[][] access;
    int result = 0;
    public int movingCount(int threshold, int rows, int cols) {
        access = new boolean[rows][cols];
        BackTracking(threshold, 0, 0);
        return result;
    }
    public void BackTracking(int threshold, int row, int col) {
        if (row < 0 || col < 0 || row >= access.length || col >= access[0].length) {
            return;
        }
        if (cal(row, col) > threshold) {
            return;
        }
        if (access[row][col] == false) {
            result++;
            access[row][col] = true;
        } else {
            return;
        }      
        BackTracking(threshold, row + 1, col);
        BackTracking(threshold, row, col - 1);
        BackTracking(threshold, row, col + 1);
        BackTracking(threshold, row - 1, col);
        return;
    }
    public int cal(int row, int col) {
        int sum = 0;
        while (row > 0) {
            sum += row % 10;
            row = row / 10;
        }
        while (col > 0) {
            sum += col % 10;
            col = col / 10;
        }
        return sum;
    }
}










