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。请问该机器人能够达到多少个格子?
     
    python 代码
     1 # -*- coding:utf-8 -*-
     2 class Solution:
     3     def __init__(self):
     4         self.number = 0
     5     def movingCount(self, threshold, rows, cols):
     6         if threshold<=0:
     7             return self.number
     8         # write code here
     9         visited = [0] * (rows * cols)
    10         self.movingCountCore(threshold, rows, cols, 0, 0, visited)
    11         return self.number
    12 
    13     def movingCountCore(self, threshold, rows, cols, row, col, visited):
    14 
    15         if self.check(threshold, rows, cols, row, col, visited):
    16             visited[row * cols + col] = 1
    17             self.number = 1 + self.movingCountCore(threshold, rows, cols, row - 1, col, visited)
    18             + self.movingCountCore(threshold, rows, cols, row, col - 1, visited)
    19             + self.movingCountCore(threshold, rows, cols, row + 1, col, visited)
    20             + self.movingCountCore(threshold, rows, cols, row, col + 1, visited)
    21         return self.number
    22 
    23     def check(self, threshold, rows, cols, row, col, visited):
    24         # 判断是否满足条件
    25         if row >= 0 and row < rows and col >= 0 and col < cols and (
    26                 self.getDigitSum(row) + self.getDigitSum(col) <= threshold) and visited[row * cols + col] == 0:
    27             return True
    28         return False
    29 
    30     def getDigitSum(self, num):
    31         sum_ = 0
    32         while num:
    33             sum_ += num % 10
    34             num = num // 10
    35         return sum_

    note:

    代码紫色不能加=,否则报错:列表越界,坐标从0开始的

    计算各位数和的方法

    1.将数转换为字符串

    1     def getDigitSum(number):
    2         sum_ = 0
    3         for i in str(number):
    4             sum_ += int(i)
    5         return sum_

    2.普通求解(在python中,/表示除法,//表示取整,%表示取余)

    1 def getDigitSum(num):
    2     sum_ = 0
    3     while num:
    4         sum_ += num % 10
    5         num = num // 10
    6     return sum_
  • 相关阅读:
    Java多线程
    2018腾讯校招软件开发岗在线笔试题
    2018京东校招Java笔试题
    计模式之中介者、观察者
    值得注意的Java基础知识
    Java的内部类
    用静态内部类实现单例模式
    String,StringBuilder区别,一个是常量,一个是可变量
    ArrayList list = new ArrayList()在这个泛型为Integer的ArrayList中存放一个String类型的对象
    List<String> list=new ArrayList<String>(20);为什么要声明为List 而不是ArrayList<String>?
  • 原文地址:https://www.cnblogs.com/shuangcao/p/13437937.html
Copyright © 2011-2022 走看看