void dfs(){
1. 检查下标是否越界,是否走出地图,访问过
2. 检查是否满足限定条件,当前坐标的值value(x,y)在约定条件。
3. 标记访问过,是否满足输出条件。
4.进行下一步dfs
5.回溯,某一个全局变量退出递归时候要回溯
}
class Solution {
public:
int rows_bound; // 行数边界
int cols_bound; // 列数边界
using V = vector<int>; // 类似类型定义
using VV = vector<V>;
int dir[5] = {1, 0, -1, 0, 1}; // 记录dfs时候的方向数组,简化代码
int check(int x){ //检查当前值是否符合要求
int sum = 0;
while(x){
sum += x%10;
x /= 10;
}
return sum;
}
// 坐标x,y ,sho 为限定值,ret:统计的结果,mark 为地图标记数组
void dfs(int x, int y, int &sho, int &ret, VV &mark){
// 边界 访问否
if(x < 0 || x >= rows_bound || y < 0 || y >= cols_bound || mark[x][y]) return;
// 当前值符合否 小于限定值
if(check(x) + check(y) > sho) return;
// 都符合 记录该值
mark[x][y] = 1;
ret++;
// 进行dfs
for(int i = 0; i < 4; i++){
dfs(x + dir[i], y + dir[i+1], sho, ret, mark);
}
// 回溯
}
int movingCount(int sho, int rows, int cols)
{
if(sho <= 0){
return 0;
}
VV mark(rows, V(cols, 0)); // rows cols 都赋值为0
int ret = 0;
rows_bound = rows;
cols_bound = cols;
dfs(0, 0, sho, ret, mark);
return ret;
}
};