题目描述
地上有一个m行和n列的方格。一个机器人从坐标0,0的格子开始移动,每一次只能向左,右,上,下四个方向移动一格,但是不能进入行坐标和列坐标的数位之和大于k的格子。 例如,当k为18时,机器人能够进入方格(35,37),因为3+5+3+7 = 18。但是,它不能进入方格(35,38),因为3+5+3+8 = 19。请问该机器人能够达到多少个格子?
解题思路
class Solution {
public:
int movingCount(int threshold, int rows, int cols)
{
if(rows == 0 || cols == 0 || threshold < 0) return 0;
vector<vector<int>> graph(rows,vector<int>(cols));
for(int i=0;i<rows;++i){
int ti = i,tsi = 0;
while(ti){
tsi += ti%10;
ti /= 10;
}
for(int j=0;j<cols;++j){
int tj = j,tsj = 0;
while(tj){
tsj += tj%10;
tj /= 10;
}
graph[i][j] = tsi + tsj;
}
}
vector<int> dx = {-1,0,1,0};
vector<int> dy = {0,1,0,-1};
queue<pair<int,int>> que;
que.push(make_pair(0,0));
graph[0][0] = threshold+1;
int ans = 1;
while(!que.empty()){
int n = que.size();
for(int i=0;i<n;++i){
int x = que.front().first;
int y = que.front().second;
que.pop();
for(int d=0;d<4;++d){
int tx = x + dx[d];
int ty = y + dy[d];
if(tx>=0&&tx<rows&&ty>=0&&ty<cols&&graph[tx][ty]<=threshold){
que.push(make_pair(tx,ty));
graph[tx][ty] = threshold+1;
++ans;
}
}
}
}
return ans;
}
};