zoukankan      html  css  js  c++  java
  • 机器人运动范围——回溯法应用

    1. 和前面矩阵路径一样,即是使用递归,探索性前进,遍历各种情况

    前面那个主函数里有循环是因为它可以从一个矩阵中的任意位置进入!!

    我们这个题是只能从起始点(0,0)进入,用不到循环,但是访问过的节点也不能继续访问了!!(0,0)也满足要求,所以最差也是count=1;

    注意:这个是行和列坐标不大于K(阈值),不是等于阈值!注意读题!

    地上有一个m行和n列的方格。一个机器人从坐标0,0的格子开始移动,每一次只能向左,右,上,下四个方向移动一格,

    但是不能进入行坐标和列坐标的数位之和大于k的格子。 例如,当k为18时,机器人能够进入方格(35,37),因为3+5+3+7 = 18。

    但是,它不能进入方格(35,38),因为3+5+3+8 = 19。请问该机器人能够达到多少个格子?

    class Solution {
    public:
        int movingCount(int threshold, int rows, int cols) //阈值
        {
        if(rows<1||cols<1||threshold<1)
            return 0;
        bool * visited=new bool[rows*cols];
        memset(visited,0,rows*cols);//全都进行置位操作
        int count= movingCountCore(threshold,rows,cols,0,0,visited);
        return count;
        }
    
    public:
        //为了通用性考虑  还是加上int row, int col 就是起始索引的位置,此处只能从0 0进   
        int movingCountCore(int threshold,int rows, int cols,int row, int col,bool *visited)
        {
            
           if(row<0||col<0||row>rows-1||col>cols-1)//边界检查
           return 0;
           int  count=0;
            
            //当前节点满足条件可以向前走
            if(check(threshold,rows,cols,row,col,visited))
            {
             visited[row*cols+col]=true;
            //首先  (0,0)这个点的位置 可以允许进是确定的   //递归搜索 
               count=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 count;
        }
    public:
       //多输入一些参数就是为了类型检查?  
       bool check(int threshold,int rows, int cols,int row, int col,bool * visited)
       {
           if(row>=0&&col>=0&&row<rows&&col<cols&&!visited[row*cols+col]&&getcheck(row)+getcheck(col)<=threshold)
           {
               return true;
           }else
              return false;  
       }
    public:
       int getcheck(int value)
       {
           
           int sum=0;
           while(value)
           {
            sum+=value%10;
               value=value/10;
           }
            return sum;   
       }
    };
  • 相关阅读:
    laravel中使用include和component方法中的一点小区别
    【解决】Converting circular structure to JSON
    NUXT中使用axios,自己项目测试记录
    iPhone“连到系统上的设备没有发挥作用”原因分析及解决方法 20200105
    vue-touch不能上下滑动的问题【解决】
    动态加载swiper,默认显示最后一个swiper-slide怎么办
    CentOS 7 修改开机等待时间
    使用IIS管理器搭建FTP服务器以及其启用虚拟主机名
    织梦后台删除子栏目不成功的解决方法
    去除织梦标签[field:image/]所产生的宽高
  • 原文地址:https://www.cnblogs.com/cgy1012/p/11376001.html
Copyright © 2011-2022 走看看