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。请问该机器人能够达到多少个格子?

     

    题解:这题我最先开始是在快手的试题上做的。也是一个比较标准的回溯。把数字拆分一下,做判断,也是进行上下左右的递归即可。记得标记数组初始化!!!!!要不是gg给我找出来,我大概卡死//

     

    代码:

     1 class Solution {
     2 public:
     3     int check(int num){
     4         int ans = 0;
     5         while(num){
     6             ans += num%10;
     7             num/=10;
     8         }
     9         return ans;
    10     }
    11     int countStep(int threshold,int rows,int cols,int row,int col,int visit[][105] ){
    12         if(row < 0|| col < 0 || row >= rows || col >= cols || visit[row][col] == 1
    13            || check(row)+check(col) > threshold) {
    14             return 0;
    15         }
    16         visit[row][col] = 1;
    17         return 1
    18             + countStep(threshold,rows,cols,row+1,col,visit)
    19             + countStep(threshold,rows,cols,row-1,col,visit)
    20             + countStep(threshold,rows,cols,row,col+1,visit)
    21             + countStep(threshold,rows,cols,row,col-1,visit);
    22     }
    23 
    24     int movingCount(int threshold, int rows, int cols){
    25         int visit[105][105];
    26         memset(visit,0,sizeof(visit));//超级重要!!!!!!!
    27         int ans = countStep(threshold,rows,cols,0,0,visit);
    28         return ans;
    29     }
    30 };
  • 相关阅读:
    消费RabbitMQ时的注意事项,如何禁止大量的消息涌到Consumer,保证线程安全
    消费RabbitMQ时的注意事项,如何禁止大量的消息涌到Consumer,保证线程安全
    scrollTop值为0等疑难杂症
    9.四平方和
    8.冰雹数
    7.搭积木
    6.凑算式
    5.分小组
    4.骰子游戏
    3.平方怪圈
  • 原文地址:https://www.cnblogs.com/Asumi/p/12431137.html
Copyright © 2011-2022 走看看