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

    题目:

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

    解答:

     1 public class Solution {
     2 
     3     public static void main(String[] args) {
     4         int threshold = 10;
     5         int rows = 3;
     6         int cols = 7;
     7 
     8         System.out.println(movingCount(threshold, rows cols));
     9     }
    10 
    11     public static int movingCount(int threshold, int rows, int cols)
    12     {
    13         if(threshold < 0 || rows <= 0 || cols <= 0) {
    14             return 0;
    15         }
    16         
    17         boolean[] visited = new boolean[rows*cols];
    18         for(int i = 0; i < rows*cols; i++) {
    19             visited[i] = false;
    20         }
    21         
    22         int count = movingCount(threshold, rows, cols, 0, 0, visited);
    23         
    24         return count;
    25     }
    26     
    27     public static int movingCount(int threshold, int rows, int cols, int row, int col, boolean[] visited){
    28         int count = 0;
    29 
    30         if(check(threshold, rows, cols, row, col, visited)) {
    31 
    32             visited[row*cols+col] = true;
    33 
    34             count = 1 + movingCount(threshold, rows, cols, row+1, col, visited)+
    35                 movingCount(threshold, rows, cols, row-1, col, visited)+
    36                 movingCount(threshold, rows, cols, row, col+1, visited)+
    37                 movingCount(threshold, rows, cols, row+1, col-1, visited);
    38         }
    39 
    40         return count;
    41     }
    42     
    43     
    44     public static boolean check(int threshold, int rows, int cols, int row, int col, boolean[] visited) {
    45         if(row >=0 && row < rows && col >= 0 && col < cols && getDigitSum(row)+getDigitSum(col) <= threshold && !visited[row*cols+col]){
    46             return true;
    47         } else {
    48             return false;
    49         }
    50     }
    51     
    52     
    53     public static int getDigitSum(int num) {
    54         
    55         int sum = 0;
    56         while(num > 0) {
    57             sum = sum + num % 10;
    58             num = num /10;
    59         }
    60         
    61         return sum;
    62     }
    63 }

  • 相关阅读:
    XOR加密作业
    2019-2020-1 20191312《信息安全专业导论》第六周学习总结
    欧几里得算法及其伪代码
    2019-2020-1 20191312《信息安全专业导论》第五周学习总结
    2019-2020-1 20191312《信息安全专业导论》第四周学习总结
    寻找你的黑客偶像作业
    2019-2020-1 20191312 《信息安全专业导论》第三周学习总结
    罗马数字转化为阿拉伯数字
    IEEE754 浮点数
    2019-2020-2 网络对抗技术 20175211 Exp6 MFS基础应用
  • 原文地址:https://www.cnblogs.com/wylwyl/p/10469226.html
Copyright © 2011-2022 走看看