class Solution {
public:
int movingCount(int threshold, int rows, int cols) {
if (rows < 1 || cols < 1) return 0;
visited = vector<vector<bool>>(rows, vector<bool>(cols, false));
int res = backtrack(threshold, rows, cols, 0, 0);
return res;
}
private:
vector<vector<bool>> visited;
int backtrack(int threshold, int rows, int cols, int r, int c) {
if (r < 0 || r >= rows || c < 0 || c >= cols
|| !getValue(r, c, threshold) || visited[r][c] == true) {
return 0;
}
visited[r][c] = true;
return 1 + backtrack(threshold, rows, cols, r+1, c) + backtrack(threshold, rows, cols, r, c+1);
}
bool getValue(int r, int c, int threshhold) {
int sum = 0;
while (r != 0) {
sum += r % 10;
r = r / 10;
}
while (c != 0) {
sum += c % 10;
c = c / 10;
}
return sum <= threshhold;
}
};