地上有一个m行和n列的方格。一个机器人从坐标0,0的格子开始移动,每一次只能向左,右,上,下四个方向移动一格,但是不能进入行坐标和列坐标的数位之和大于k的格子。 例如,当k为18时,机器人能够进入方格(35,37),因为3+5+3+7 = 18。但是,它不能进入方格(35,38),因为3+5+3+8 = 19。请问该机器人能够达到多少个格子?
#####理解:
此题拿到手首先是一个棋牌扫描的问题,每一块都需要考虑向上、下、左、右四个方向延展,肯定会用到递归的思路,把问题聚焦到每一个棋牌格点来考虑。因为要对扫描过的格点进行规避,所以要设置flag数组进行标记。在movingCount方法中定义好flag数组,调用递归函数即可。
把递归的部分放到movingCountCore方法中进行处理,处理的顺序很重要,首先要对false的情况充分考虑到,给予递归终止条件;之后再通过4组递归对相邻的格点进行扫描,需要注意的是**,一定不要忘记最后的“+1”,这个1是格点本身的计数**。
因为这个题要求是数位和,需要将一个数字中的各个数位提取出来进行求和,千万不要错看为数字序号本身。这里用传统方法写了一个numSum方法。
public class Solution {
public int movingCount(int threshold, int rows, int cols)
{
int[][] flag = new int[rows][cols];
return movingCountCore(threshold, rows, cols, 0, 0, flag);
}
private int movingCountCore(int threshold, int rows, int cols, int i, int j, int[][] flag){
if(i<0 || j<0 || i>=rows || j>=cols || flag[i][j] ==1 || numSum(i)+numSum(j)>threshold){
return 0;
}
flag[i][j] = 1;
return movingCountCore(threshold, rows, cols, i+1, j, flag)
+ movingCountCore(threshold, rows, cols, i-1, j, flag)
+ movingCountCore(threshold, rows, cols, i, j+1, flag)
+ movingCountCore(threshold, rows, cols, i, j-1, flag)
+1; //这里的1很关键,一定不能忘掉,这是最底层的单元计数
}
private int numSum(int k){
int result = 0;
while(k > 0){
result += k%10;
k = k/10;
}
return result;
}
}