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

    剑指offer 66.机器人的运动范围

    题目

    地上有一个m行和n列的方格。一个机器人从坐标0,0的格子开始移动,每一次只能向左,右,上,下四个方向移动一格,但是不能进入行坐标和列坐标的数位之和大于k的格子。 例如,当k为18时,机器人能够进入方格(35,37),因为3+5+3+7 = 18。但是,它不能进入方格(35,38),因为3+5+3+8 = 19。请问该机器人能够达到多少个格子?

    思路

    这种题目可以设置标记位,上下左右四个方向可以设置为4个式子,返回值相加。
    先假设全局为0,表示未走过,然后向四个方向走,若走过了,返回数字加一,继续走,若没走或者不能走,就去除这一条路(返回0)。

    代码

      public int movingCount(int threshold, int rows, int cols) {
        int flag[][] = new int[rows][cols];
        return find(0, 0, rows, cols, flag, threshold);
      }
    
      public int find(int i, int j, int rows, int cols, int[][] flag, int threshold) {
        if (i < 0 || i >= rows || j < 0 || j >= cols || sum(i) + sum(j) > threshold
            || flag[i][j] == 1) {
          return 0;
        }
        flag[i][j] = 1;
        return find(i - 1, j, rows, cols, flag, threshold)
            + find(i + 1, j, rows, cols, flag, threshold)
            + find(i, j - 1, rows, cols, flag, threshold)
            + find(i, j + 1, rows, cols, flag, threshold)
            + 1;
      }
    
      public int sum(int i) {
        int sum = 0;
        while (i > 0) {
          sum += i % 10;
          i /= 10;
        }
        return sum;
      }
    
  • 相关阅读:
    mybatis05--多条件的查询
    mybatis04--Mapper动态代理实现
    mybatis03--字段名和属性名不一致
    mybatis02--增删改查
    myBatis01
    hibernate12--缓存
    hibernate11--Criteria查询
    hibernate10--命名查询
    hibernate09--连接查询
    (转载)閱讀他人的程式碼(5)找到程式入口,再由上而下抽絲剝繭
  • 原文地址:https://www.cnblogs.com/blogxjc/p/12427807.html
Copyright © 2011-2022 走看看