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

    题目描述

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

    思路 与上题类似:
    机器人从左边(0,0)开始移动,当它准备进入(i,j)的格子时候,通过检查坐标的数位和来判断机器人是否能够进入。如果机器人能够进入坐标(i,j)的格子,我们接着判断它能否进入四个相邻的格子。

     1 public class Solution {
     2     public int movingCount(int threshold, int rows, int cols){
     3         boolean[] flag =  new  boolean[rows*cols];
     4         int count = help(threshold,rows,cols,0,0,flag);
     5         return count;
     6     }
     7     private int help(int threshold,int rows,int cols,int i, int j ,boolean[] flag){
     8         int count = 0;
     9         int index = i*cols+j;
    10         int sum = Sum(i)+Sum(j);
    11         if(i<0||i>=rows||j<0||j>=cols||flag[index]==true||sum>threshold)
    12             return 0;  
    13         flag[index] = true;
    14         count = 1 + help(threshold,rows,cols,i-1,j,flag)
    15             + help(threshold,rows,cols,i+1,j,flag)
    16             + help(threshold,rows,cols,i,j-1,flag)
    17             + help(threshold,rows,cols,i,j+1,flag);
    18         return count;
    19     }
    20     private int Sum(int num){
    21         int sum = 0;
    22         while(num>0){
    23             sum+=num%10;
    24             num/=10;
    25         }
    26         return sum;
    27     }
    28 }
  • 相关阅读:
    希尔排序算法
    直接插入排序和折半插入排序算法
    快排序算法
    部分博文目录索引(C语言+算法)
    Gnome排序算法
    选择排序算法
    pip运行报错Fatal error in launcher: Unable to create process using pip.exe
    Java Selenium封装--RemoteWebDriver
    Java Selenium封装--RemoteWebElement
    selenium webdriver自动化对日期控件的处理
  • 原文地址:https://www.cnblogs.com/zle1992/p/8318748.html
Copyright © 2011-2022 走看看