题目:地上有一个m行和n列的方格。一个机器人从坐标0,0的格子开始移动,每一次只能向左,右,上,下四个方向移动一格,但是不能进入行坐标和列坐标的数位之和大于k的格子。 例如,当k为18时,机器人能够进入方格(35,37),因为3+5+3+7 = 18。但是,它不能进入方格(35,38),因为3+5+3+8 = 19。请问该机器人能够达到多少个格子?
注意第10行i/10.0>=0.1,若直接写成10,在python2下运行错误。
思路:回溯法,只判断向右向下这两个方向。
class Solution:
def movingCount(self, threshold, rows, cols):
self.row = rows
self.col = cols
list_=[]
self.search(list_, threshold, 0, 0)
return len(list_)
def sum(self, sum, i):
while i / 10.0 >= 0.1:
sum += i % 10
i = int(i / 10)
return sum
def check(self, i, j, threshold):
sum=0
sum = self.sum(sum, i)
sum = self.sum(sum, j)
if sum <= threshold:
return True
else:
return False
def search(self, dict_, threshold, i, j):
if not self.check(i, j, threshold) or (i, j) in dict_:
return
dict_.append((i, j))
if j != self.col-1 and self.check(i, j+1, threshold):
self.search(dict_, threshold, i, (j+1))
if i != self.row-1and self.check(i+1, j, threshold):
self.search(dict_, threshold, (i+1), j)