题目描述
地上有一个m行和n列的方格。一个机器人从坐标0,0的格子开始移动,每一次只能向左,右,上,下四个方向移动一格,但是不能进入行坐标和列坐标的数位之和大于k的格子。
例如,当k为18时,机器人能够进入方格(35,37),因为3+5+3+7 = 18。但是,它不能进入方格(35,38),因为3+5+3+8
= 19。请问该机器人能够达到多少个格子。
解题思路
看到这种题目中出现左,右,上,下的题第一反应就是联想到dfs和bfs来解题,既然是用遍历来实现,那就要找到停止遍历的终止条件,这道题的终止条件为越界、重复、及机器人的坐标X的个位数加十位数再加上Y的个位数加十位数不能大于给定的K值,而涉及到个位数十位数我们马上就可以联想到用%运算,所以这道题的解题思路就出来了。
代码实现
public class Solution {
public int movingCount(int threshold, int rows, int cols)
{
int [][]flag=new int[rows][cols];
helper(0,0,rows,cols,threshold,flag);
return count;
}
//判断是否符合要求
public boolean isValid(int rows,int cols,int threshold){
int sum=0;
while(rows>0){
sum+=rows%10;
rows=rows/10;
}
while(cols>0){
sum+=cols%10;
cols=cols/10;
}
if(sum>threshold) return false;
else return true;
}
private int count=0;
private void helper(int i,int j,int rows,int cols,int threshold,int[][]flag){
if(i<0||i>=rows||j<0||j>=cols) return;//不符合则不计数
if(flag[i][j]==1) return;//坐标被访问了不能计数
if(!isValid(i,j,threshold)){//坐标不符合不计数同时要标志为已访问
flag[i][j]=1;
return;
}
flag[i][j]=1;
count++;
//左右上下遍历
helper(i-1,j,rows,cols,threshold,flag);
helper(i+1,j,rows,cols,threshold,flag);
helper(i,j-1,rows,cols,threshold,flag);
helper(i,j+1,rows,cols,threshold,flag);
}
}