题目:机器人的运动范围
题目描述
地上有一个m行和n列的方格。一个机器人从坐标0,0的格子开始移动,每一次只能向左,右,上,下四个方向移动一格,但是不能进入行坐标和列坐标的数位之和大于k的格子。 例如,当k为18时,机器人能够进入方格(35,37),因为3+5+3+7 = 18。但是,它不能进入方格(35,38),因为3+5+3+8 = 19。请问该机器人能够达到多少个格子?
思路
写个函数递归,注意出口,flag判断是否已经走过。
class Solution {
public:
int movingCount(int threshold, int rows, int cols)
{
if(threshold<0 || rows<=0 || cols<=0) return 0;
vector<vector<bool> > flag;
for(int i=0;i<rows;i++){
vector<bool> one_row;
for(int j=0;j<cols;j++){
one_row.push_back(false);
}
flag.push_back(one_row);
}
return dfs(0,0,threshold,flag,rows,cols);
}
int dfs(int x,int y,int k,vector<vector<bool> > &flag, int rows,int cols){
if(x<0 || x>=rows || y<0 || y>=cols || !judge(x,y,k) || flag[x][y]) return 0;
flag[x][y]=true;
return dfs(x+1,y,k,flag,rows,cols)+
dfs(x-1,y,k,flag,rows,cols)+
dfs(x,y+1,k,flag,rows,cols)+
dfs(x,y-1,k,flag,rows,cols)+1;
}
bool judge(int x,int y, int k){
int sum=0;
while(x){
sum = sum + (x%10);
x = x/10;
}
while(y){
sum = sum + (y%10);
y = y/10;
}
return sum<=k;
}
};