标准的dfs。
class Solution {
public:
int getSum(int n){//数字各位求和
int sum = 0;
for(int m = 1; m <= n; m *= 10){
sum += (n/m) % 10;
}
return sum;
}
void movingCount(int threshold, int rows, int cols, bool* flag,
int i, int j, int& count){
int index = i * cols + j;
if(i < 0 || j < 0 || i >= rows || j >= cols || flag[index])
return;//边界判断
int sum = getSum(i) + getSum(j);
if(sum > threshold)//阈值判断
return;
flag[index] = true;//记录该节点
++count;
movingCount(threshold, rows, cols, flag, i-1, j, count);//递归访问
movingCount(threshold, rows, cols, flag, i+1, j, count);//上下左右
movingCount(threshold, rows, cols, flag, i, j-1, count);
movingCount(threshold, rows, cols, flag, i, j+1, count);
return;
}
int movingCount(int threshold, int rows, int cols)
{
bool *flag = new bool[rows*cols];//记录是否已经访问过
memset(flag, false, rows*cols*sizeof(bool));//初始化
int count = 0;//统计访问总数
movingCount(threshold, rows, cols, flag, 0, 0, count);//左上角开始
return count;
}
};