地上有一个m行n列的方格,一个机器人从坐标(0, 0)的格子开始移动。
它每次可以向左、右、上、下移动一格,但不能进入行坐标和列坐标的数位之和大于k的格子。
请问该机器人能够到达多少个格子?
要求得可到达的格子数目,可使用递归的方式向左、向右、向上、向下依次展开,通过集合添加的方式来避免重复,符合要求的才累计次数。通常物体或者人在二维方格运动这类问题都可以用回溯法解决。
class Solution:
def __init__(self):
self.visited = None
def moving_count(self, threshold, rows, cols):
return self.moving(threshold, rows, cols, 0, 0)
def moving(self, threshold, rows, cols, row, col):
if row // 10 + row % 10 + col // 10 + col % 10 > threshold:
return 0
if row < 0 or row >= rows or col < 0 or col >= cols:
return 0
if self.visited is None:
self.visited = set() # 避开重复用集合,没必要用字典增加空间
# print(self.visited, len(self.visited))
if (row, col) in self.visited:
return 0
self.visited.add((row, col))
return 1 + self.moving(threshold, rows, cols, row-1, col) + \
self.moving(threshold, rows, cols, row+1, col) +\
self.moving(threshold, rows, cols, row, col-1) +\
self.moving(threshold, rows, cols, row, col+1)
st = Solution()
threshold, rows, cols = 7, 5, 5
print(st.moving_count(threshold, rows, cols))
(最近更新:2019年09月21日)
3301

被折叠的 条评论
为什么被折叠?



