剑指 Offer 13. 机器人的运动范围 - 力扣(LeetCode) (leetcode-cn.com)
class Solution {
int m, n, k;
vector<vector<bool>> not_visited;
public:
int movingCount(int M, int N, int K) {
m = M; n = N; k = K;
not_visited = vector<vector<bool>>(M);
for (auto& r : not_visited) r = vector<bool>(N, true);
int count = 0;
spread(0, 0, count);
return count;
}
void spread(int x, int y, int& count) {
if (x >= 0 && y >= 0 && x < m && y < n &&
not_visited[x][y] && s(x) + s(y) <= k) {
not_visited[x][y] = false;
++count;
spread(x - 1, y, count);
spread(x + 1, y, count);
spread(x, y - 1, count);
spread(x, y + 1, count);
}
}
int s(int x) {
int sum = 0;
while (x) {
sum += x % 10;
x /= 10;
}
return sum;
}
};