欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 新闻 > 社会 > leetcode994.腐烂的橘子

leetcode994.腐烂的橘子

2025/5/7 4:09:24 来源:https://blog.csdn.net/weixin_74175349/article/details/146887112  浏览:    关键词:leetcode994.腐烂的橘子

思路源自

【力扣hot100】【LeetCode 994】腐烂的橘子|多源BFS

这里图中的腐烂的的橘子是同时对周围进行腐化,所以采用多源bfs就能解决 

多源bfs与单源bfs的区别就在于队列取出时一轮是取出队列当中的全部元素

class Solution {public int orangesRotting(int[][] grid) {int[][] dirs = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};//记录四个方向int result=0;//记录需要的分钟数int fresh=0;//记录新鲜橘子的数目Queue<int[]> queue = new ArrayDeque<>();//队列存储腐烂橘子int m = grid.length, n = grid[0].length;for (int i = 0; i < m; i++) {for (int j = 0; j < n; j++) {if(grid[i][j]==1)fresh++;else if(grid[i][j]==2)queue.add(new int[]{i, j});}}while (!queue.isEmpty()) {int len = queue.size();while (len-- != 0) {int[] coordinate = queue.remove();//腐化四个方向上的新鲜橘子for (int[] dir : dirs) {int x = coordinate[0] + dir[0];int y = coordinate[1] + dir[1];if(x<0||y<0||x>=m||y>=n||grid[x][y]!=1)continue;queue.add(new int[]{x, y});grid[x][y]=2;fresh--;}}if(!queue.isEmpty())//下一轮还有result++;}if(fresh>0)return -1;elsereturn result;}
}

 

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

热搜词