class Solution {
public:
int movingCount(int threshold, int rows, int cols)
{
if(threshold<0 || rows<1 || cols<1) return 0;
int row=0, col=0;
bool* visited = new bool[rows*cols];
for(int i=0; i<rows*cols; i++) {
visited[i] = false;
}
return movingCountCore(threshold, rows, cols, row, col, visited);
}
// 递归函数,给定起点触发有几个格子
int movingCountCore(int threshold, int rows, int cols,
int row, int col, bool* visited) {
int countFromHere = 0;
if(row>=0 && row<rows && col>=0 && col<cols
&& !visited[row*cols+col]
&& canEnter(threshold, row, col) ){
visited[row*cols+col] = true;
countFromHere = 1
+ movingCountCore(threshold, rows, cols, row+1, col, visited)
+ movingCountCore(threshold, rows, cols, row-1, col, visited)
+ movingCountCore(threshold, rows, cols, row, col+1, visited)
+ movingCountCore(threshold, rows, cols, row, col-1, visited);
}
return countFromHere;
}
// 特定格子是否满足条件
bool canEnter(int threshold, int row, int col) {
bool flag = false;
if(getDigitalSum(row) + getDigitalSum(col) <= threshold) {
flag = true;
}
return flag;
}
// 算一个int各位相加
int getDigitalSum(int number) {
int sum = 0;
while(number>0) {
sum += number % 10;
number /= 10;
}
return sum;
}
};
看了一眼书上的思路(函数划分),自己写的。第二次过。
第一次没过的原因是自定义的函数声明忘写函数返回值类型...js的恶习。
写完后看了一下书上的解法,它把row>=0 && row<rows && col>=0 && col<cols && !visited[row*cols+col]这些条件放在了canEnter这个函数里。私以为还是我这样比较好。一来canEnter可以单纯的当作一个判断两个数是否满足各位相加<=threshold的一个函数(既然这样,我的函数名可以改成与题目无关),与题目关系不大了。这样函数功能划分好一点而且传参还少。
总结:书上给出了多写函数的榜样,这点非常值得学习。一个函数只负责一个小功能,有利于代码可读性和可维护性。
写完这道题我对递归又熟练了一些。加油吧~
二刷:
感觉四个相邻格子相加那里有点问题,题意有点模糊。如果题意允许这个机器人多次出发,求它最多可到达的范围,那么这样加起来没问题,约束只有一次移动一格。
如果题意是找一条路径最长的走法,求最长路径,那么感觉四个方向应该求max,而且不是max的路径涉及到回溯visited=0.这样的话问题就很复杂了。
所以,如果按第一种,这叫回溯吗:) 没有矩阵中的路径那个题“回溯”
三刷
再次强调:不要放弃思考,你能写出来的,并且写得更好!!
class Solution {
public:
int movingCount(int threshold, int rows, int cols)
{
bool* visited = new bool[rows*cols];
memset(visited, 0, rows*cols);
int count = 0;
startFrom(threshold, rows, cols, 0, 0, count, visited);
return count;
}
void startFrom(int threshold, int rows, int cols,
int row, int col, int& count, bool* visited) {
if(row<0 || row>rows-1 || col<0 || col>cols-1) return;
if(visited[row*cols+col]) return;
if(bitSum(row) + bitSum(col) <= threshold) {
count++;
visited[row*cols+col] = true;
startFrom(threshold, rows, cols, row+1, col, count, visited);
startFrom(threshold, rows, cols, row-1, col, count, visited);
startFrom(threshold, rows, cols, row, col-1, count, visited);
startFrom(threshold, rows, cols, row, col+1, count, visited);
}
}
int bitSum(int num) {
int result = 0;
while(num != 0) {
result += num%10;
num = num/10;
}
return result;
}
};
2个坑:
bool
* visited =
new
bool
[rows][cols];这样初始化数组就不行,提示数组长度不是常量,很奇怪;
没加memset
(visited, 0, rows*cols);时候,答案是随机的,好奇怪!