爽歪歪666
不以物喜,不以己悲,努力才是永恒的主题。

题目描述

地上有一个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_

 

posted on 2020-08-05 09:52  爽歪歪666  阅读(76)  评论(0编辑  收藏  举报