原题链接
- 思路
- C++代码
1.首先将机器人放到第一格位置,从第一格判断结束后分别对周围所有格子在进行判断。同时为了防止格子被重复判断,要新建立一个bool类数组来标记格子是否走过。
2.为了使代码的逻辑性更强,我们把这个过程分成三部,用三个函数来实现,①从起点开始,往下递归,②判断其是否越界以及格子是否被走过,③将格子所在的行列的数字拆分后求和与题中的threshold对比
class Solution {
public:
int movingCount(int threshold, int rows, int cols) {
if(threshold<0||rows<0||cols<0)//先进行安全性判断
{
return 0;
}
bool* Path=new bool[rows*cols];//记录是否走过的数组
memset(Path,0,sizeof(bool)*rows*cols);
int cout=FindCount(threshold,rows,cols,Path,0,0);
delete[]Path;
return cout;
}
int FindCount(int threshold,int rows,int cols,bool*Path,int row,int col)
{
int cout=0;
if(IsTruePath(threshold,rows,cols,Path,row,col))
{
Path[row*cols+col]=true;//格子可以走,标记已走过
//注意Path数组表示row行col列,每行固定为cols个数据
//依次递归判断周围格子
cout=1+FindCount(threshold,rows,cols,Path,row+1,col)
+FindCount(threshold,rows,cols,Path,row-1,col)
+FindCount(threshold,rows,cols,Path,row,col+1)
+FindCount(threshold,rows,cols,Path,row,col-1);
}
return cout;
}
bool IsTruePath(int threshold,int rows,int cols,bool*Path,int row,int col)
//判断格子是否符合标准
{
if(row>=0&&row=0&&col 


