题目描述
地上有一个m行和n列的方格。一个机器人从坐标0,0的格子开始移动,每一次只能向左,右,上,下四个方向移动一格,但是不能进入行坐标和列坐标的数位之和大于k的格子。 例如,当k为18时,机器人能够进入方格(35,37),因为3+5+3+7 = 18。但是,它不能进入方格(35,38),因为3+5+3+8 = 19。请问该机器人能够达到多少个格子?
简单深搜即可,直接遍历更快一点,锻炼一下用java写深搜,注意java中的成员变量!!!
public class Solution {
private int sum = 0;
private int N,M;
private int vis[][] = new int [100][100];
private int dirx[] = {0,0,1,-1};
private int diry[] = {1,-1,0,0};
public int movingCount(int threshold, int rows, int cols)
{
N = rows; M = cols;
dfs(threshold,0,0);
return sum;
}
public boolean judge(int threshold,int n,int m)
{
int key = 0;
while(n>0)
{
key=key+(n%10);
n/=10;
}
while(m>0)
{
key=key+(m%10);
m/=10;
}
if(threshold>=key)
return true;
return false;
}
public boolean ok(int n,int m)
{
if(n<0||m<0||n>=N||m>=M)
return false;
if(vis[n][m]==1)
return false;
return true;
}
public void dfs(int threshold,int n,int m)
{
if(judge(threshold,n,m)==false||ok(n,m)==false)
return;
sum++;
vis[n][m] = 1;
for(int i=0;i<4;i++)
dfs(threshold,n+dirx[i],m+diry[i]);
}
}
来源:CSDN
作者:sakura_is_the_best
链接:https://blog.csdn.net/sakura_is_the_best/article/details/103749290