JZ66 机器人的运动范围 python

JZ66 机器人的运动范围

在这里插入图片描述
my version
dfs
错误记录

  1. a = b = [x for x in range(n)] 会使a、b指向同一空间
  2. 由于机器人从[0,0]开始运动,因此只有向右和向下两个方向可以走
class Solution:
    def dfs(self, i, j, thre, rows, cols):
#         print(i,j)
        if i<0 or i>=rows or j<0 or j>=cols or self.visit[i][j]:
            # 超出边界/已访问过
            return
        
        row, col = i, j
        i_sum = j_sum = 0
        while row:
            i_sum += row % 10
            row = row // 10
        while col:
            j_sum += col % 10
            col = col // 10
        if i_sum+j_sum>thre:
            # 不满足要求
            return
        
        self.visit[i][j] = 1
#         print('visit',self.visit)
        # 左下右上
#         self.dfs(i, j-1, thre, rows, cols)
        self.dfs(i+1, j, thre, rows, cols)
        self.dfs(i, j+1, thre, rows, cols)
#         self.dfs(i-1, j, thre, rows, cols)
        
    def movingCount(self, threshold, rows, cols):
        self.visit = [[0 for i in range(cols)] for i in range(rows)]
        self.dfs(0, 0, threshold, rows, cols)
        res = 0
        for i in range(rows):
            for j in range(cols):
                res += self.visit[i][j]
        return res

DFS与BFS模板

其他题解
bfs

from queue import Queue

class Solution:
    def index_sum(self,i, j):
        res = 0
        while i:
            res += i % 10
            i = i // 10
        while j:
            res += j % 10
            j = j // 10
        return res
    def movingCount(self, threshold, rows, cols):
        q = Queue()
        visit = [[0 for i in range(cols)] for i in range(rows)]
        res = 0
        if rows and cols:
            q.put((0,0))
            while not q.empty():
                i,j = q.get()
                if i<0 or i>=rows or j<0 or j>=cols or visit[i][j] or self.index_sum(i,j)>threshold:
                    continue
                visit[i][j] = 1
                res += 1
                q.put((i, j+1))
                q.put((i+1,j))
        return res
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值