• LeetCode220726_52、腐烂的橘子


    在给定的 m x n 网格 grid 中,每个单元格可以有以下三个值之一:

    值 0 代表空单元格;
    值 1 代表新鲜橘子;
    值 2 代表腐烂的橘子。
    每分钟,腐烂的橘子 周围 4 个方向上相邻 的新鲜橘子都会腐烂。

    返回 直到单元格中没有新鲜橘子为止所必须经过的最小分钟数。如果不可能,返回 -1 。

    示例 1:

    图1 腐烂的橘子示例图 

    输入:grid = [[2,1,1],[1,1,0],[0,1,1]]
    输出:4

    来源:力扣(LeetCode)
    链接:https://leetcode.cn/problems/rotting-oranges
    著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

    题解,BFS寻找感染最短距离,记录新鲜橘子数量,用以返回判断,遍历时,一轮一轮感染,每次将一层队列内的烂橘子全部整完在进行下一轮。

    1. class Solution{
    2. public int orangesRotting(int[][] grid){
    3. int count = 0;
    4. Queue<int[]> queue = new LinkedList<>();
    5. for(int i = 0; i < grid.length; i++){
    6. for(int j = 0; j < grid[0].length; j++){
    7. if(grid[i][j] == 1){
    8. count++;
    9. } else if(grid[i][j] == 2){
    10. queue.offer(new int[]{i,j});
    11. }
    12. }
    13. }
    14. int round = 0;
    15. while(count > 0 && !queue.isEmpty()){
    16. round++;
    17. int size = queue.size();
    18. for(int m = 0; m < size; m++){
    19. int[] pos = queue.poll();
    20. int x = pos[0];
    21. int y = pos[1];
    22. int[] dx = {1, 0, 0, -1};
    23. int[] dy = {0, -1, 1, 0};
    24. for(int n = 0; n < 4; n++){
    25. int nextx = x + dx[n];
    26. int nexty = y + dy[n];
    27. if(nextx >= 0 && nextx < grid.length && nexty >= 0 && nexty < grid[0].length && grid[nextx][nexty] == 1){
    28. grid[nextx][nexty] = 2;
    29. count--;
    30. queue.offer(new int[]{nextx,nexty});
    31. }
    32. }
    33. }
    34. }
    35. if(count == 0){
    36. return round;
    37. }else{
    38. return -1;
    39. }
    40. }
    41. }

  • 相关阅读:
    深度概括:这应该是介绍时序异常检测最全的了
    Apache-Doris单机部署
    基于STM32结合CubeMX学习Free-RT-OS的源码之深入学习软件定时器实现过程
    Java泛型的总结
    安装nginx
    MongoDB与Pymongo深度实践:从基础概念到无限级评论应用示例
    手机+卫星的科技狂想
    【编译原理】词法分析
    基于Open3D和PyTorch3D读取三维数据格式OBJ
    Exception : Content-Type cannot contain wildcard type ‘*‘
  • 原文地址:https://blog.csdn.net/Zoro_666/article/details/126003529