zoukankan      html  css  js  c++  java
  • 66 机器人的运动范围

    题目描述

    地上有一个m行和n列的方格。一个机器人从坐标0,0的格子开始移动,每一次只能向左,右,上,下四个方向移动一格,但是不能进入行坐标和列坐标的数位之和大于k的格子。 例如,当k为18时,机器人能够进入方格(35,37),因为3+5+3+7 = 18。但是,它不能进入方格(35,38),因为3+5+3+8 = 19。请问该机器人能够达到多少个格子?
     
    思路:利用一个访问数组,以及访问的位置就设置为true,结合一个判断合法的if语句,不合法的情况就返回0,相当于可以回退,找到所有可以到达的位置
     
    class Solution {
    public:
        bool isvalid(int threshold,int x,int y){
            int sum = 0;
            while(x != 0){
                sum += x % 10;
                x = x / 10;
            }
            while(y != 0){
                sum += y % 10;
                y = y / 10;
            }
            if(sum > threshold){
                return false;
            }
            return true;
        }
        
        int helper(int threshold, int rows, int cols,vector<bool> &visited,int startx,int starty){
            if(startx < 0 || starty < 0 || startx >= rows || starty >= cols || !isvalid(threshold,startx,starty) || visited[startx * cols + starty]){
                return 0;//不合法的情况,有加1减一,所以要和0以及上限比较
            }
            visited[startx * cols + starty] = true;//访问的位置设置为已访问,这样判断不合法的时候,下次就返回0,不会重复计算
            return helper(threshold,rows,cols,visited,startx,starty - 1) +
                   helper(threshold,rows,cols,visited,startx,starty + 1) +
                   helper(threshold,rows,cols,visited,startx - 1,starty) +
                   helper(threshold,rows,cols,visited,startx + 1,starty) + 1;//上下左右访问,进入到这里的说明可以加1(之前没访问)
                
        }
        
        int movingCount(int threshold, int rows, int cols){
           if(threshold <= 0 || rows <= 0 || cols <= 0){ 
               return 0;
           }
           int res = 0;
           vector<bool> visited(rows * cols,false);
           res = helper(threshold,rows,cols,visited,0,0);
           return res;        
        }
    };
  • 相关阅读:
    Ansible template中j2文件调用var中定义变量报错解决办法
    Ansible 获取hosts中的分组ip
    VUE UI网站汇总
    vue rules详解与实例
    Python 获取设备ip地址
    Flask && Vue 虚拟机申请平台(从开发到部署)
    Vue 把获取到的可编辑表格的值传给后端
    SQLAlchemy基本使用,创建表,增删改查
    Ansible 角色(roles)一键部署redis集群(三主三从)
    Flask 数据库相关操作
  • 原文地址:https://www.cnblogs.com/dingxiaoqiang/p/8482204.html
Copyright © 2011-2022 走看看