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

    题目描述
    地上有一个m行和n列的方格。一个机器人从坐标0,0的格子开始移动,每一次只能向左,右,上,下四个方向移动一格,但是不能进入行坐标和列坐标的数位之和大于k的格子。 例如,当k为18时,机器人能够进入方格(35,37),因为3+5+3+7 = 18。但是,它不能进入方格(35,38),因为3+5+3+8 = 19。请问该机器人能够达到多少个格子?
     
    解题思路:先判断(i,j)格子是否能进入,如果能判断(i,j-1),(i,j+1),(i-1,j),(i+1,j)四个格子是否能进入
     1 class Solution {
     2 public:
     3     int getDigitSum(int num)
     4     {
     5         int sum = 0;
     6         while(num > 0)
     7         {
     8             sum += num%10;
     9             num = num/10;
    10         }
    11         return sum;
    12     }
    13     bool checked(int threshold,int rows,int cols,int row,int col, bool *visit)
    14     {
    15         if(row>=0 && row<rows && col>=0 && col <cols && getDigitSum(row)+getDigitSum(col)<=threshold && !visit[row*cols+col])
    16             return true;
    17         return false;
    18     }
    19     int movingCountCore(int threshold,int rows,int cols,int row,int col,bool *visit)
    20     {
    21         int count = 0;
    22         if(checked(threshold,rows,cols,row,col,visit))
    23         {
    24             visit[row*cols+col] = true;
    25             count = 1 + movingCountCore(threshold,rows,cols,row-1,col,visit) +
    26                         movingCountCore(threshold,rows,cols,row+1,col,visit) +
    27                         movingCountCore(threshold,rows,cols,row,col-1,visit) +
    28                         movingCountCore(threshold,rows,cols,row,col+1,visit);
    29         }
    30         return count;
    31     }
    32     int movingCount(int threshold, int rows, int cols)
    33     {
    34         bool *visit = new bool[rows*cols];
    35         memset(visit,0,rows*cols);
    36         int count = movingCountCore(threshold,rows,cols,0,0,visit);
    37         delete[] visit;
    38         return count;
    39     }
    40 };
  • 相关阅读:
    HashMap的存储原理
    HashSet的存储原理
    ArrayList的底层实现原理
    $.getJSON()不执行回调函数
    JavaScript学习笔记(一)
    【转】日语口语简略型总结(更新中。。。)
    计算机常用符号(日文)更新中。。。
    异常
    注解
    多线程
  • 原文地址:https://www.cnblogs.com/qqky/p/7125997.html
Copyright © 2011-2022 走看看