class Solution {
public:
int movingCount(int m, int n, int k) {
if (k==0)
return 1;
vector<vector<bool>> valid(m, vector<bool>(n, true));// 记录该位置是否被访问过
return dfs(valid, m, n, 0, 0, k);
}
int dfs(vector<vector<bool>>& valid, int m, int n, int row, int col, int k)
{
int sum = getSum(row) + getSum(col);
// 如果越界,或者和大于k,或者已被访问过了,返回0
if (row>=m || col>=n || sum>k || !valid[row][col])
return 0;
valid[row][col] = false;//该位置状态变为:已访问过
return 1+dfs(valid, m, n, row+1, col, k) + dfs(valid, m, n, row, col+1, k);
}
int getSum(int num)
{
// 求某个数字所有位数相加的和
if (num<10)
return num;
int sum = 0;
while (num>0)
{
sum += num % 10;
num = num /10;
}
return sum;
}
};