力扣热题52

994. 腐烂的橘子 - 力扣(LeetCode)https://leetcode.cn/problems/rotting-oranges/submissions/628761183/?envType=study-plan-v2&envId=top-100-liked广度遍历

利用队列先记录所有腐烂的橘子的位置和当前的时间,然后从队列中取出橘子位置和时间,把四周的橘子也腐烂并加入队列,直到队列没元素,最后循环遍历一下差错判断一下并输出时间

复制代码
#python
class Solution:
    def orangesRotting(self, grid: List[List[int]]) -> int:
        h,l=len(grid),len(grid[0])
        q=collections.deque()
        for i,row in enumerate(grid):
            for j,k in enumerate(row):
                if k==2:
                    q.append((i,j,0))
        
        def ab(i,j):
            for a,b in ((i-1,j),(i+1,j),(i,j-1),(i,j+1)):
                if 0<=a<h and 0<=b<l:
                    yield a,b
        t=0
        while q:
            i,j,t=q.popleft()
            for a,b in ab(i,j):
                if grid[a][b]==1:
                    grid[a][b]=2
                    q.append((a,b,t+1))
        if any(1 in i for i in grid):
            return -1
        return t
相关推荐
CoderIsArt7 小时前
C#中UI 线程与 Dispatcher
开发语言·ui·c#
AI情绪识别开源10 小时前
检信 ALLEMOTION OS 加密打包可执行程序 — 全面测试报告版本: v1.3功能测试 / 性能测试 /
开发语言·数据结构·人工智能·功能测试
lupai10 小时前
手机在网状态接口实测效果与质量评估
大数据·python·智能手机·api接口
「QT(C++)开发工程师」11 小时前
C++ auto 用法详解
开发语言·c++
OPEN-F11 小时前
C++STL教程:容器适配器与实用工具
开发语言·c++
yaoxin52112311 小时前
507. Java 反射 - 在 BeanFactory 中实现依赖注入
java·开发语言
OPEN-F11 小时前
C++模板教程:变参模板、折叠表达式与SFINAE
java·开发语言·c++
有点。11 小时前
C++二叉搜索树进阶
开发语言·c++
HugoStudio_SWAN11 小时前
【擦除重绘】C++ 控制台动画:弹跳 Logo DVD 屏保效果
开发语言·c++·学习·程序人生