地上有一个m行和n列的方格。一个机器人从坐标0,0的格子开始移动,每一次只能向左,右,上,下四个方向移动一格,但是不能进入行坐标和列坐标的数位之和大于k的格子。 例如,当k为18时,机器人能够进入方格(35,37),因为3+5+3+7 = 18。但是,它不能进入方格(35,38),因为3+5+3+8 = 19。请问该机器人能够达到多少个格子?
C++
class Solution {
public:
int get_sum(int num)
{
int res=0;
while(num)
{
res+=num%10;
num/=10;
}
return res;
}
void dfs(int threshold, int rows, int cols, vector<vector<int>>& flag, int& ans, int r, int c)
{
if(0==flag[r][c])
{
int dx[]={1,-1,0,0};
int dy[]={0,0,1,-1};
flag[r][c]=1;
int sum=get_sum(r)+get_sum(c);
if(sum<=threshold)
{
ans++;
for(int k=0;k<4;k++)
{
int y=r+dy[k];
int x=c+dx[k];
if(y>=0 && y<rows && x>=0 && x<cols)
{
dfs(threshold,rows,cols,flag,ans,y,x);
}
}
}
}
return;
}
int movingCount(int threshold, int rows, int cols)
{
vector<vector<int>> flag(rows,vector<int>(cols,0));
int ans=0;
dfs(threshold,rows,cols,flag,ans,0,0);
return ans;
}
};
来源:CSDN
作者:我很忙2010
链接:https://blog.csdn.net/qq_27060423/article/details/103987508