DFS。
class Solution {
public:
int n, m;
int single_sum(int x) {
int res = 0;
while (x) {
res += x % 10;
x /= 10;
}
return res;
}
int sum(int x, int y) {
return single_sum(x) + single_sum(y);
}
bool check(int x, int y) {
return x >= 0 && x < n && y >=0 && y < m;
}
int dfs(int x, int y, int k, vector<vector<bool>> &vis) {
if (sum(x, y) > k) return 0;
vis[x][y] = true;
int res = 1;
int dx[] = {-1, 0 ,1, 0}, dy[] = {0, 1, 0, -1};
for (int i = 0; i < 4; i++) {
int a = x + dx[i], b = y + dy[i];
if (check(a, b) && !vis[a][b])
res += dfs(a, b, k, vis);
}
return res;
}
int movingCount(int n, int m, int k) {
this->n = n, this->m = m;
vector<vector<bool>> vis(n, vector<bool>(m));
return dfs(0, 0, k, vis);
}
};