1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
|
class Solution {
public:
int movingCount(int threshold, int rows, int cols)
{
if(rows <= 0 || cols<=0) return 0;
queue<pair<int,int>> q;
q.push({0,0});
vector<vector<bool>> vis(rows+1,vector<bool>(cols + 1));
int res= 0;
int dx[4] = {-1, 0, 1, 0}, dy[4] = {0, 1, 0, -1};
while(q.size()) {
auto u = q.front();q.pop();
int x = u.first, y = u.second;
if(vis[x][y] || getSum(x,y) > threshold) continue;
vis[x][y] = true;
++res;
for(int i=0;i<4;++i) {
int nx = x+dx[i],
ny = y+dy[i];
if(nx<0 || nx>=rows || ny<0 || ny>=cols) continue;
q.push({nx,ny});
}
}
return res;
}
int getSum(int x,int y) {
int s = 0;
while(x) s += x%10,x/=10;
while(y) s+= y%10,y/=10;
return s;
}
};
|