class Solution {
public:
int movingCount(int m, int n, int k) {
vector<vector<bool>>vis(m,vector<bool>(n,false));
int dx[4] = {-1,1,0,0};
int dy[4] = {0,0,1,-1};
queue<pair<int,int>>q;
q.push(make_pair(0,0));
vis[0][0] = true;
int ans = 1;
while(!q.empty())
{
auto it = q.front();
q.pop();
for(int i = 0;i<4;i++)
{
int tx = it.first + dx[i];
int ty = it.second + dy[i];
if(isSafe(tx,ty,m,n,k) && !vis[tx][ty])
{
vis[tx][ty] = true;
ans++;
q.push(make_pair(tx,ty));
}
}
}
return ans;
}
bool isSafe(int i,int j,int m,int n,int k)
{
int x = i,y = j,sum = 0;
while(x)
{
sum += x%10;
x/=10;
}
while(y)
{
sum += y%10;
y/=10;
}
return i>=0 && i<m && j>=0 && j<n && sum <= k;
}
};
剑指 Offer 13. 机器人的运动范围
最新推荐文章于 2023-10-06 10:25:23 发布