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 cnt;
     4     int movingCount(int threshold, int rows, int cols) {
     5         bool *flag = new bool[rows * cols];
     6         memset(flag, 0, sizeof(bool)*rows * cols);
     7         cnt = 0;
     8         moving(threshold, rows, cols, 0, 0, flag);
     9         return cnt;
    10     }
    11     void moving(int threshold, int rows, int cols, int i, int j, bool* flag) {
    12         if(i >= 0 && i < rows && j >= 0 && j < cols && getsum(i) + getsum(j) <= threshold && flag[i * cols + j] == false) {
    13             flag[i * cols + j] = true;
    14             cnt++;
    15             moving(threshold, rows, cols, i + 1, j, flag);
    16             moving(threshold, rows, cols, i - 1, j, flag);
    17             moving(threshold, rows, cols, i, j - 1, flag);
    18             moving(threshold, rows, cols, i, j + 1, flag);
    19         }
    20     }
    21     int getsum(int num) {
    22         int sum = 0;
    23         while(num) {
    24             sum += num % 10;
    25             num /= 10;
    26         }
    27         return sum;
    28     }
    29 };
  • 相关阅读:
    UPNP报文示例
    ceph旧版客户端挂载新版ceph报错
    VUE——配置本地运行指定不同环境
    springBoot——Web开发简介【七】
    C++ 浮点数的存储与精度
    端口复用与惊群效应
    MySQL5.5读写分离之mysql-proxy
    Mysql读写分离--mysql-proxy
    mysql主从之keepalive+MySQL高可用
    如何在CentOS 7上安装Htop
  • 原文地址:https://www.cnblogs.com/jacen789/p/7747815.html
Copyright © 2011-2022 走看看