地上有一个 m 行和 n 列的方格,横纵坐标范围分别是 0∼m−1 和 0∼n−1。
一个机器人从坐标0,0的格子开始移动,每一次只能向左,右,上,下四个方向移动一格。
但是不能进入行坐标和列坐标的数位之和大于 k 的格子。
请问该机器人能够达到多少个格子?
样例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。
注意:
0<=m<=50
0<=n<=50
0<=k<=100
class Solution {
public:
int getsum(pair<int,int> p){
int x=p.first;
int y=p.second;
int sum=0;
while(x){
sum+=x%10;
x/=10;
}
while(y){
sum+=y%10;
y/=10;
}
return sum;
}
int movingCount(int threshold, int rows, int cols)
{
if(!rows||!cols)return 0;
vector<vector<bool>>st(rows,vector<bool>(cols));
queue<pair<int,int>>q;
q.push({0,0});
st[0][0]=true;
int cnt=0;
int dx[4]={-1,0,1,0},dy[4]={0,1,0,-1};
while(q.size()){
auto t=q.front();
q.pop();
if(getsum(t)>threshold)continue;//不能用这个点更新周围的点
cnt++;
for(int i=0;i<4;i++){
int a=t.first+dx[i],b=t.second+dy[i];
if(a>=0&&a<rows&&b>=0&&b<cols&&!st[a][b]){
st[a][b]=true;
q.push({a,b});
}
}
}
return cnt;
}
};
class Solution {
public:
int getsum(pair<int,int> p){
int x=p.first;
int y=p.second;
int sum=0;
while(x){
sum+=x%10;
x/=10;
}
while(y){
sum+=y%10;
y/=10;
}
return sum;
}
int movingCount(int threshold, int rows, int cols)
{
if(!rows||!cols)return 0;
vector<vector<bool>>st(rows,vector<bool>(cols));
queue<pair<int,int>>q;
q.push({0,0});
st[0][0]=true;
int cnt=0;
int dx[4]={-1,0,1,0},dy[4]={0,1,0,-1};
while(q.size()){
auto t=q.front();
q.pop();
cnt++;
for(int i=0;i<4;i++){
int a=t.first+dx[i],b=t.second+dy[i];
if(a>=0&&a<rows&&b>=0&&b<cols&&!st[a][b]
&&getsum({a,b})<=threshold){
st[a][b]=true;
q.push({a,b});
}
}
}
return cnt;
}
};