题目描述
地上有一个m行和n列的方格。一个机器人从坐标0,0的格子开始移动,每一次只能向左,右,上,下四个方向移动一格,但是不能进入行坐标和列坐标的数位之和大于k的格子。 例如,当k为18时,机器人能够进入方格(35,37),因为3+5+3+7 = 18。但是,它不能进入方格(35,38),因为3+5+3+8 = 19。请问该机器人能够达到多少个格子?
//bfs
class Solution {
public:
int offset[4][2]={1,0,0,1,-1,0,0,-1};
int movingCount(int threshold, int rows, int cols)
{
if(rows<0||cols<0||threshold<0) return 0;
int maxbit=getbit(max(rows,cols));
if(maxbit<=0||threshold==0) return 1;
int state[rows][cols];
memset(state,0,sizeof(state));
int step=1;
state[0][0]=1;
queue<pair<int,int> >q;
q.push(pair<int,int>(0,0));
while(!q.empty())
{
pair<int,int>front=q.front();
q.pop();
for(int i=0;i<4;++i)
{
int x=front.first+offset[i][0];
int y=front.second+offset[i][1];
if(x<0||x>=rows||y<0||y>=cols||state[x][y]==1)
continue;
int sum=0,tempx=x,tempy=y;
for(int j=0;j<maxbit;++j)
{
sum+=tempx%10+tempy%10;
tempx/=10;
tempy/=10;
}
if(sum>threshold) continue;
state[x][y]=1;
++step;
q.push(pair<int,int>(x,y));
}
}
return step;
}
private:
int getbit(int num)
{
if(num<=0) return 0;
int res=0;
while(num)
{
++res;
num/=10;
}
return res;
}
};