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

    题目描述

    地上有一个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         if (threshold < 0 || rows < 1 || cols < 1)return 0;
     6         int res = 0;
     7         vector<bool>visit(rows*cols, false);
     8         DFS(threshold, rows, cols, 0, 0, visit, res);
     9         return res;
    10     }
    11     void DFS(const int threshold, const int rows, const int cols, int i, int j, vector<bool>&visit, int &res)
    12     {
    13         int s = 0, tempI = i, tempJ = j;
    14         while (tempI)
    15         {
    16             s += tempI % 10;
    17             tempI /= 10;
    18         }
    19         while (tempJ)
    20         {
    21             s += tempJ % 10;
    22             tempJ /= 10;
    23         }
    24         if (i >= 0 && i < rows && j >= 0 && j < cols && s <= threshold && visit[i*cols + j] == false)
    25         {
    26             res++;
    27             visit[i*cols + j] = true;
    28             DFS(threshold, rows, cols, i + 1, j, visit, res);
    29             DFS(threshold, rows, cols, i - 1, j, visit, res);
    30             DFS(threshold, rows, cols, i, j + 1, visit, res);
    31             DFS(threshold, rows, cols, i, j - 1, visit, res);
    32         }
    33     }
    34 };
  • 相关阅读:
    js相关小实例——滚动监听
    js相关小实例——进度条
    数据库的连接
    php函数
    php语法
    php基础上
    列表 选择背景变化
    飞入
    移动列表内容
    javascript的语法
  • 原文地址:https://www.cnblogs.com/zzw1024/p/11655080.html
Copyright © 2011-2022 走看看