题目描述
地上有一个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);
}
}
这篇博客讨论了一个编程问题,其中机器人在m行n列的网格中从坐标(0,0)开始移动,每次可以向左、右、上、下移动一格,但不能进入行坐标和列坐标的数位之和大于k的格子。博客提供了解决方案,通过一个名为`movingCount`的公共方法来计算机器人能够到达的格子数。方法中使用了深度优先搜索,并通过`isValid`辅助方法来检查坐标是否合法。最后返回计数器`count`作为结果。
456

被折叠的 条评论
为什么被折叠?



