【菜鸟向】机器人的运动范围(LeetCode)

在这里插入图片描述
忍不住感叹自己太过naive。一开始想的极为简单:遍历矩阵,判断是否满足k条件。但是提交不过去,于是发现陷阱。

当机器人因为k条件不能通过时,会导致一些点,机器人无法继续到达(因为只能前后左右运动)

于是换个思路,一步一步的走。走一步之后判断他的四个方向是否可前行(不行就空着)然后走到下一个点,继续如此判断(走过的点flag置1,避免重复计算)。

class Solution:
    def movingCount(self, m: int, n: int, k: int) -> int:
        # 计算位数的和
        def sum(a, b):
            sum = 0
            while a:
                sum += a % 10
                a //= 10
            while b:
                sum += b % 10
                b //= 10
            return sum

        from collections import deque
        flag = [[0 for _ in range(n)] for _ in range(m)] 
         # flag矩阵 判断机器人是否到达,已到达为1
        flag[0][0] = 1 
         # 0,0位置设为1
        temp = deque()
        temp.append([0, 0])
        res = 0
        while temp:
            temp_point = temp.popleft()
            res += 1
            x, y = temp_point
            for x_bias, y_bias in [[0, 1], [0, -1], [1, 0], [-1, 0]]:
                new_x = x + x_bias
                new_y = y + y_bias
                if new_x < 0 or new_x > m - 1 or new_y < 0 or new_y > n - 1 or sum(new_x, new_y) > k or flag[new_x][new_y] == 1:
                    continue
                flag[new_x][new_y] = 1
                temp.append([new_x, new_y])
        return res
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值