class Solution {
public:
int getDigitSum(int number) {
int sum = 0;
while(number) {
sum+=number%10;
number/=10;
}
return sum;
}
int movingCountCore(int threshold, int rows, int cols, int row, int col, vector<vector<bool> >& visit) {
if (row < 0 || row >= rows || col < 0 || col >= cols) return 0;
int count = 0;
if (!visit[row][col] && getDigitSum(row)+getDigitSum(col) <= threshold) {
visit[row][col] = true;
++ count;
const int dx[4] = {-1, 0, 1, 0};
const int dy[4] = {0, 1, 0, -1};
for (int i = 0; i < 4; ++ i) {
count += movingCountCore(threshold, rows, cols, row+dx[i], col+dy[i], visit);
}
}
return count;
}
int movingCount(int threshold, int rows, int cols)
{
if (threshold <= 0 || rows <=0 || cols <= 0) return 0;
vector<vector<bool> > visit(rows, vector<bool>(cols, false));
return movingCountCore(threshold, rows, cols, 0, 0, visit);
}
};