题目描述
地上有一个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 movingCount(int threshold, int rows, int cols)
{
if(threshold < 0)
return 0;
int dx[] = {1, -1, 0, 0};
int dy[] = {0, 0, 1, -1};
int res = 1;
queue<pair<int, int> > q;
int visit[rows * cols + 5];
memset(visit, 0, sizeof(visit));
visit[0] = 1;
q.push(make_pair(0, 0));
while(!q.empty())
{
int newX;
int newY;
pair<int, int> temp = q.front();
q.pop();
for(int i = 0; i < 4; i++)
{
newX = temp.first + dx[i];
newY = temp.second + dy[i];
if(newX < 0 || newX >= cols || newY < 0 || newY >= rows)
continue;
if(!isOk(newX, newY, threshold))
continue;
if(visit[newY * cols + newX] == 1)
continue;
res++;
visit[newY * cols + newX] = 1;
q.push(make_pair(newX, newY));
}
}
return res;
}
bool isOk(int x, int y, int judge)
{
int res = 0;
while(x != 0)
{
res = res + x % 10;
x /= 10;
}
while(y != 0)
{
res = res + y % 10;
y /= 10;
}
if(res > judge)
{
return false;
}
else
{
return true;
}
}
};