栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

剑指offer

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

剑指offer

原题链接

文章目录
    • 思路
    • C++代码

思路

1.首先将机器人放到第一格位置,从第一格判断结束后分别对周围所有格子在进行判断。同时为了防止格子被重复判断,要新建立一个bool类数组来标记格子是否走过。
2.为了使代码的逻辑性更强,我们把这个过程分成三部,用三个函数来实现,①从起点开始,往下递归,②判断其是否越界以及格子是否被走过,③将格子所在的行列的数字拆分后求和与题中的threshold对比

C++代码
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
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/284001.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号