zoukankan      html  css  js  c++  java
  • 剑指offer---机器人的运动范围

    题目:机器人的运动范围

    要求:地上有一个m行和n列的方格。一个机器人从坐标0,0的格子开始移动,每一次只能向左,右,上,下四个方向移动一格,但是不能进入行坐标和列坐标的数位之和大于k的格子。 例如,当k为18时,机器人能够进入方格(35,37),因为3+5+3+7 = 18。但是,它不能进入方格(35,38),因为3+5+3+8 = 19。请问该机器人能够达到多少个格子?

    1 class Solution {
    2 public:
    3     int movingCount(int threshold, int rows, int cols)
    4     {
    5         
    6     }
    7 };

    解题代码:

     1 class Solution {
     2 public:
     3     int movingCount(int threshold, int rows, int cols) {
     4         if(threshold < 0 || rows <= 0 || cols <= 0)
     5             return 0;
     6 
     7         // 初始化
     8         bool *visited = new bool[rows * cols];
     9         for(int i=0; i<rows*cols; i++){
    10             visited[i] = false;
    11         }
    12 
    13         int count = movingCountCore(threshold, rows, cols, 0, 0, visited);
    14         delete[] visited;
    15         return count;
    16     }
    17 
    18 private:
    19     int  movingCountCore(int threshold, int rows, int cols, int row, int col, bool *visited){
    20         int count = 0;
    21         if(check(threshold, rows, cols, row, col, visited)){
    22             visited[row*cols+col] = true;
    23             count = 1 + movingCountCore(threshold, rows, cols, row-1, col, visited)
    24                     + movingCountCore(threshold, rows, cols, row+1, col, visited)
    25                     + movingCountCore(threshold, rows, cols, row, col-1, visited)
    26                     + movingCountCore(threshold, rows, cols, row, col+1, visited);
    27         }
    28         return count;
    29     }
    30 
    31     // 检查是否满足进入(row, col)的条件
    32     bool check(int threshold, int rows, int cols, int row, int col, bool *visited){
    33         if(row >= 0 && col >= 0 && row < rows && col < cols && !visited[row*cols+col]
    34             && getDigitSum(row)+getDigitSum(col) <= threshold){
    35             return true;
    36         }
    37         else
    38             return false;
    39     }
    40 
    41     // 求解数位和
    42     int getDigitSum(int num){
    43         int sum = 0;
    44         while(num > 0){
    45             sum += num % 10;
    46             num /= 10;
    47         }
    48         return sum;
    49     }
    50 };
  • 相关阅读:
    PHP IDE NetBeans代码主题和除掉竖线解决方案
    初识Python
    从LazyPhp说起
    从Pycharm说起
    准备系统地研究一下"高性能网站开发",挑战很大,希望能坚持到底!
    IIS日志分析[资源]
    见一好东西:Threaded WebDownload class with Progress Callbacks
    ASP.net Application 中使用域用户登录
    看图找错
    汉字转拼音缩写的函数(C#)
  • 原文地址:https://www.cnblogs.com/iwangzhengchao/p/9853582.html
Copyright © 2011-2022 走看看