题目描述
地上有一个m行和n列的方格。一个机器人从坐标0,0的格子开始移动,每一次只能向左,右,上,下四个方向移动一格,但是不能进入行坐标和列坐标的数位之和大于k的格子。 例如,当k为18时,机器人能够进入方格(35,37),因为3+5+3+7 = 18。但是,它不能进入方格(35,38),因为3+5+3+8 = 19。请问该机器人能够达到多少个格子?
- dfs求注意里面的count每次要更新一次哟; 里面代用isOk函数
- 调用isOk来判断新探索的点是否合法
- 判断是否合法需要 viseted 和 在合理的范围内;和get_sum和小于threshold的值
- visited d[4][2]四周探索;
class Solution {
private:
vector<vector<bool>>visited;
int d[4][2]={{-1,0},{0,1},{1,0},{0,-1}};
int get_sum(int x)
{
int sum=0;
while(x>0)
{
sum+=x%10;
x=x/10;
}
return sum;
}
bool isOk(int threshold, int rows, int cols,int x,int y,vector<vector<bool>>&visited)
{
if(x>=0&&x<rows&&y>=0&&y<cols&&!visited[x][y])
{
if(get_sum(x)+get_sum(y)<=threshold)
return true;
}
return false;
}
int dfs(int threshold, int rows, int cols,int x,int y,vector<vector<bool>>&visited)
{
int count=0;
if(isOk(threshold,rows,cols,x,y,visited))
{
visited[x][y]=true;
count+=1;//注意这里面要加1;
for(int i=0;i<4;i++)
{
int newx=x+d[i][0];
int newy=y+d[i][1];
count+=dfs(threshold,rows,cols,newx,newy,visited);
}
}
return count;
}
public:
int movingCount(int threshold, int rows, int cols)
{
if(threshold<=0||rows<=0||cols<=0)
return 0;
visited=vector<vector<bool>>(rows,vector<bool>(cols,false));
int res=dfs(threshold,rows,cols,0,0,visited);
return res;
}
};