LeetCdoe 刷题记录 994.腐烂的橘子 BFS解法

有不足之处请多多指教

在这里插入图片描述
BFS模板:

#(1).不需要确定当前遍历到了哪一层
dirs = [[1,0],[-1,0],[0,-1],[0,1]]
while queue:
    point = queue.pop(0)
    for 节点 in cur的所有相邻节点:
        if 该节点有效且未访问过:
        queue.append(该节点)
#(2).需要确定当前遍历到了哪一层
dirs = [[1,0],[-1,0],[0,-1],[0,1]]
level = 0
while queue 不空:
    size = queue.size()
    for i in range(size)
        cur = queue.pop(0)
        for 节点 in cur的所有相邻节点:
            if 该节点有效且未被访问过:
                queue.append(该节点)
    level += 1

本题需要确定遍历的层次
即题中:全部腐烂需要几分钟

代码

class Solution:
    def orangesRotting(self, grid: List[List[int]]) -> int:
        lenx, leny = len(grid), len(grid[0])
        dirs = [[1,0],[-1,0],[0,1],[0,-1]]  #每次腐烂是按照上下左右四个方向进行
        queue = []
        fresh = 0
        for i in range(lenx):
            for j in range(leny):
                if grid[i][j] == 2:
                    queue.append([i,j])  #初始化队列中元素
                if grid[i][j] == 1:
                    fresh += 1           #新鲜橘子的个数
        if fresh == 0: return 0
        leval = 0                        #分钟数
        while queue and fresh > 0:       #套用模板
            size = len(queue)
            for i in range(size):
                x, y = queue.pop(0)
                #向四个方向腐烂
                for dirx,diry in dirs:
                    newx, newy = x + dirx, y + diry
                    #符合范围且橘子还是新鲜的(1)执行将坐标加入队列并将橘子变为腐烂(0)
                    #同时新鲜橘子数目-1
                    if 0 <= newx < lenx and 0 <= newy < leny and grid[newx][newy] == 1:
                        grid[newx][newy] = 2
                        queue.append([newx,newy])
                        fresh -= 1
            leval += 1
        if fresh > 0:   #如果还有橘子腐烂不了,即题中的不可能使所有橘子腐烂,返回-1
            return -1
        else:
            return leval
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值