bfs
class Solution {
public:
bool judge(int x, int y, int k) {
int tmp = 0;
while (x > 0) {
tmp += x % 10;
x /= 10;
}
while (y > 0) {
tmp += y % 10;
y /= 10;
}
return tmp <= k;
}
int movingCount(int m, int n, int k) {
const int maxn = 105;
bool visit[maxn][maxn] = {false};
queue<pair<int, int>> que;
que.push(make_pair(0, 0));
visit[0][0] = true;
int ans = 1;
m--;
n--;
const int x_add[] = {0, 0, -1, 1};
const int y_add[] = {1, -1, 0, 0};
while (!que.empty()) {
const int &x = que.front().first;
const int &y = que.front().second;
for (int i = 0; i < 4; i++) {
const int now_x = x + x_add[i];
const int now_y = y + y_add[i];
if (0 <= now_x && now_x <= n && 0 <= now_y && now_y <= m && !visit[now_x][now_y] && judge(now_x, now_y, k)) {
ans++;
visit[now_x][now_y] = true;
que.push(make_pair(now_x, now_y));
}
}
que.pop();
}
return ans;
}
};