地上有一个 m 行和 n 列的方格,横纵坐标范围分别是 0∼m−1 和 0∼n−1。
一个机器人从坐标 (0,0)的移动,每一次只能向左,右,上,下四个方向移动一格。
但是不能进入行坐标和列坐标的数位之和大于 kk 的格子。
请问该机器人能够达到多少个格子?
注意:
0<=m<=50
0<=n<=50
0<=k<=100
样例1
输入:k=7, m=4, n=5
输出:20
样例2
输入:k=18, m=40, n=40
输出:1484
解释:当k为18时,机器人能够进入方格(35,37),因为3+5+3+7 = 18。
但是,它不能进入方格(35,38),因为3+5+3+8 = 19。
class Solution {
public:
int get(int x,int y)
{
int res=0;
while(x)
{
res+=x%10;
x/=10;
}
while(y)
{
res+=y%10;
y/=10;
}
return res;
}
int movingCount(int threshold, int rows, int cols)
{
if(!rows||!cols)return 0;
int ans=0;
vector<vector<bool>> s(rows,vector<bool> (cols,false));
queue<pair<int ,int >> t;
t.push({0,0});
while(t.size())
{
auto tmp=t.front();
t.pop();
if(s[tmp.first][tmp.second]||get(tmp.first,tmp.second)>threshold)continue;
ans++;
s[tmp.first][tmp.second]=true;
int dx[]={1,0,-1,0},dy[]={0,-1,0,1};
for(int i=0;i<4;i++)
{
int a=tmp.first+dx[i],b=tmp.second+dy[i];
if(a>=0&&a<rows&&b>=0&&b<cols){
t.push({a,b});
}
}
}
return ans;
}
};