首页 > 分享 > BFS算法解决橘子腐烂问题:广度优先遍历求最短变质时间

BFS算法解决橘子腐烂问题:广度优先遍历求最短变质时间

OJ---腐烂的橘子

最新推荐文章于 2025-09-25 11:57:07 发布

原创 于 2022-04-20 16:07:18 发布 · 452 阅读

· 0

· 0 ·

CC 4.0 BY-SA版权

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。

运用广度优先搜索(BFS)

class Solution { public int orangesRotting(int[][] grid) { int count=0;//记录新鲜橘子 int N = grid.length;//记录数组的行 int M = grid[0].length;//记录数组的列 Queue<int[]> queue = new LinkedList<>(); for(int i=0;i<N;i++){ for(int j=0;j<M;j++){ if(grid[i][j]==1){ count++; }else if(grid[i][j]==2){ queue.add(new int[]{i,j}); } } } int time = 0;//记时间 while(!queue.isEmpty() && count>0){ time++; int n = queue.size(); for(int i=0;i<n;i++){ int[] arr = queue.poll(); int a = arr[0];//代表烂橘子的左右 int b = arr[1];//代表烂橘子的上下 if(a-1>=0 && grid[a-1][b]==1){ count--; grid[a-1][b] = 2; queue.add(new int[]{a-1,b}); } if(a+1<N && grid[a+1][b]==1){ count--; grid[a+1][b] = 2; queue.add(new int[]{a+1,b}); } if(b-1>=0 && grid[a][b-1]==1){ count--; grid[a][b-1] = 2; queue.add(new int[]{a,b-1}); } if(b+1<M && grid[a][b+1]==1){ count--; grid[a][b+1] = 2; queue.add(new int[]{a,b+1}); } } } if(count>0){ return -1; }else { return time; } } }

java

运行

相关知识

腐烂橘子扩散算法
leetcode994(c++):腐烂的橘子
腐烂的橘子BFS算法解析
【力扣日记】994 腐烂的橘子
【物流配送中的最短路径算法】:优化配送,降低成本
基本的视觉化方法有哪些
【免费】中山大学大学生程序设计竞赛2>=
疫情之下,LeetCode994“腐烂的橘子”告诉我们为什么要“少聚集”
橘子腐烂算法解析
决策树import numpy as np from copy import deepcopy class DecisionTree(object): def

网址: BFS算法解决橘子腐烂问题:广度优先遍历求最短变质时间 https://m.huajiangbk.com/newsview2376015.html

所属分类:花卉
上一篇: #南京爆料#【“天使...
下一篇: 脐橙树出现了花叶,结出来的果子是