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 };
  • 相关阅读:
    03 python学习笔记-文件操作
    02 Python学习笔记-基本数据类型
    01 Python简介、环境搭建及包管理
    一、如何使用postman做接口测试笔记一
    django测试开发-1.开始Hello django!
    Oracle创建用户并给用户授权查询指定表或视图的权限
    ORA-00933 UNION 与 ORDER BY
    excel设置单元格不可编辑
    oracle之分组内的字符串连接
    10 款强大的JavaScript图表图形插件推荐
  • 原文地址:https://www.cnblogs.com/qqky/p/7125997.html
Copyright © 2011-2022 走看看