剑指Offer:机器人的运动范围(Python语言实现)

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

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值