图论之腐烂橘子_BFS(python)

复制代码
from typing import List
from collections import deque
def orangesRotting(grid:List[List[int]])->int:
    t=0
    q=deque()  #队列,将腐烂橘子入队
    fresh=0  #统计新鲜橘子
    rows=len(grid)
    cols=len(grid[0])
    dirs=[(0,1),(0,-1),(1,0),(-1,0)]  #上下左右四个方向

    #先把腐烂橘子入队列,统计新鲜橘子数量
    for i in range(rows):
        for j in range(cols):
            if grid[i][j]==2:
                q.append((i,j))  #腐烂橘子坐标入队
            elif grid[i][j]==1:
                fresh+=1
                
    while q and fresh>0:
        q_len=len(q)
        for _ in range(q_len):
            r0,c0=q.popleft()  #取出腐烂橘子坐标(i,j)
            for k in dirs:  #判断它四个方向的橘子
                r=r0+k[0]
                c=c0+k[1]
                if r<0 or r>=rows or c<0 or c>=cols or grid[r][c]!=1:
                    continue
                grid[r][c]=2  #将新鲜橘子变坏
                q.append((r,c))  #腐烂橘子加入队列
                fresh-=1  #新鲜橘子减一
        t+=1
    return -1 if fresh else t

                
def main():
    grid= [[2,1,1],[1,1,0],[0,1,1]]  #答案输出4
    t=orangesRotting(grid)
    print(t)
    return

if __name__=="__main__":
    main()

思路:多源BFS搜索

1.使用队列,将腐烂橘子入队,每次取出一个腐烂橘子,就判断它的四个方向上的橘子是否是新鲜橘子,若是,则扩散腐烂,然后入队列,新鲜橘子数量减一。

2.如果最后还有新鲜橘子,则返回-1。

相关推荐
happylifetree2 小时前
Python09:核心语法-数据存储与运算-字面量
python
心之语歌2 小时前
Tkinter 画布基本梳理
运维·服务器·python
Wx-bishekaifayuan2 小时前
django个性化旅游路线推荐平台49005-计算机课程设计、毕业设计
spring boot·后端·python·django·课程设计·express·旅游
小白快快跑哦3 小时前
python-字符串全解(六):正则表达式-量词
python·正则表达式·字符串
禹凕4 小时前
机器学习之Selenium(Machina Learning about Selenium)
爬虫·python·selenium·测试工具·机器学习
ebiobiz6 小时前
基于 GD32 Embedded Builder (GEB) 与 Nimmake 的 MCU 工程搭建指南
c++·python·单片机·嵌入式硬件·mcu
老歌老听老掉牙6 小时前
穿越时空的物流密码:VRP与VRPTW的深度剖析及实战求解
python·物流·vrp
FYKJ_20106 小时前
django电影推荐系统55066-计算机课程设计、毕业设计
vue.js·spring boot·python·mysql·typescript·spark·django
ShyanZh6 小时前
【Python3基础】13-Python 常用设计模式
开发语言·python·设计模式
小静AI工程实验室7 小时前
RSA 算法详解:从模幂原理到 OAEP 加密、PSS 签名与 Python 实验
python·算法