题目描述
地上有一个m行和n列的方格。一个机器人从坐标0,0的格子开始移动,每一次只能向左,右,上,下四个方向移动一格,但是不能进入行坐标和列坐标的数位之和大于k的格子。 例如,当k为18时,机器人能够进入方格(35,37),因为3+5+3+7 = 18。但是,它不能进入方格(35,38),因为3+5+3+8 = 19。请问该机器人能够达到多少个格子?
经典题
个人感觉结题要点在于找到为题需要传哪些参数
然后是判断退出循环条件
以及需要返回参数是什么
public class Solution {
public int count =0;
public int movingCount(int threshold, int rows, int cols)
{
int[][] matrix = new int[rows][cols];
helper(0,0,threshold,matrix,rows,cols);
return count;
}
private 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 void helper(int i,int j , int threshod,int[][] matrixFlag, int rows, int cols){
if (i<0||i>=rows||j<0||j>=cols){
return;
}
if (matrixFlag[i][j]==1){
return;
}
if (!isValid(i,j,threshod)){
return;
}
matrixFlag[i][j]=1;
count++;
//遍历上下左右
//向上
helper(i-1,j,threshod,matrixFlag,rows,cols);
//向下
helper(i+1,j,threshod,matrixFlag,rows,cols);
//向左
helper(i,j-1,threshod,matrixFlag,rows,cols);
//向右
helper(i,j+1,threshod,matrixFlag,rows,cols);
}
}