题目:
class Solution { //本题的思路为递归法
public:
int cal(int i){ //先写个计算位数和的函数cal
int sum = 0;
while(i){
sum+=i%10;
i/=10;
}
return sum;
}
void traversal(int i, int j, int m, int n, int k, int& result, vector<vector<bool>>& visited){ //注意递归传入的参数有点多,顺序不要乱。result和visited必须要有&引用符号
if(i<0||j<0||i>=m||j>=n||cal(i)+cal(j) > k||visited[i][j]) return; //递归终止条件,也就是走到了不符合条件的格子:1.超出边界 2.位数和大于k 3.格子已经被访问过
visited[i][j] = true; //该格子符合条件,标记为true
result++; //结果+1
traversal(i+1, j, m, n, k, result, visited); //按照四个方向进行递归
traversal(i-1, j, m, n, k, result, visited);
traversal(i, j+1, m, n, k, result, visited);
traversal(i, j-1, m, n, k, result, visited);
}
int movingCount(int m, int n, int k) {
int result = 0; //初始化result
vector<vector<bool>> visited(m, vector<bool>(n, false)); //初始化visited标记矩阵
traversal(0, 0, m, n, k, result, visited);
return result;
}
};
标签:13,递归,Offer,int,机器人,traversal,result,cal,visited
From: https://www.cnblogs.com/fly-smart/p/17623943.html