int movingCount(int threshold, int rows, int cols)
{
//记录是否已经走过
//用vector构造一个二维数组
vector<vector<int> > flag(rows + 1);
for(int i = 0; i < rows + 1; ++i)
{
flag[i].resize(cols + 1, 0);
}
//初始调用
//初始输入
return helper(0, 0, rows, cols, flag, threshold);
}
int helper(int i, int j, int rows, int cols, vector<vector<int> >& flag, int threshold)
{
//验证合法性
//也是递归的结束条件
if (i < 0 || i >= rows
|| j < 0 || j >= cols
|| numSum(i) + numSum(j) > threshold
|| flag[i][j] == 1)
{
return 0;
}
flag[i][j] = 1;
return helper(i - 1, j, rows, cols, flag, threshold) //向右
+ helper(i + 1, j, rows, cols, flag, threshold) //向左
+ helper(i, j - 1, rows, cols, flag, threshold) //向下
+ helper(i, j + 1, rows, cols, flag, threshold) //向上
+ 1;
}
int numSum(int i)
{
int sum = 0;
do {
// % 10 摘取最后一位
// / 10 去掉最后一位
sum += i % 10;
}while((i = i / 10) > 0);
return sum;
}