LeetCode 994. 腐烂的橘子 (BFS)

文章目录

题目

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

值 0 代表空单元格;
值 1 代表新鲜橘子;
值 2 代表腐烂的橘子。

  • 每分钟,任何与腐烂的橘子(在 4 个正方向上)相邻的新鲜橘子都会腐烂。

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

示例 1:

在这里插入图片描述

输入:[[2,1,1],[1,1,0],[0,1,1]]
输出:4
示例 2
输入:[[2,1,1],[0,1,1],[1,0,1]]
输出:-1
解释:左下角的橘子(第 2 行, 第 0 列)永远不会腐烂,因为腐烂只会发生在 4 个正向上。

题解

  • BFS 通常用于求解最短路径问题,BFS 先搜索到的结点,一定是距离最近的结点。
  • 首先遍历数组,统计新鲜橘子个数,同时将坏橘子放入队列
  • 分别遍历坏橘子上下左右,同时每一次 新鲜橘子减一 count--,并将其加入队列

代码

package luoguArray;

import java.util.LinkedList;
import java.util.Queue;

public class P0994 {

	public static void main(String[] args) {
         int [][] grid = {{2,1,1},{1,1,0},{0,1,1}}  ;
         System.out.println(fun(grid));
		
	}

	
	public static int fun(int[][] grid) {
		int m = grid.length ;
		int n = grid[0].length ;
		
		Queue<int[]> queue = new LinkedList<>() ;
		
		// 首先遍历数组,统计新鲜橘子个数,同时将坏橘子放入队列
		
		int count = 0;
		for(int i = 0 ; i < m ;i++) {
			for(int j =0 ; j < n ;j++) {
				if(grid[i][j] == 1) {
					count ++ ;
				} else if(grid[i][j] == 2) {
					queue.add(new int[] {i,j}) ;
				}
			}
		}
		
		
		int round = 0 ;
		while(count > 0 && !queue.isEmpty()) {
			round ++ ;
		    int size = queue.size();
			  
		        for (int i = 0; i < size; i++) {
		        	
		            int[] orange = queue.poll() ;    // 出队
		            int r = orange[0];
		            int c = orange[1];
		            
		            // 上
		            if (r-1 >= 0 && grid[r-1][c] == 1) {
		                grid[r-1][c] = 2;
		                count--;
		                queue.add(new int[]{r-1, c});
		            }
		            
		            // 下
		            if (r+1 < m && grid[r+1][c] == 1) {
		                grid[r+1][c] = 2;
		                count--;
		                queue.add(new int[]{r+1, c});
		            }
		            
		            //左
		            if (c-1 >= 0 && grid[r][c-1] == 1) {
		                grid[r][c-1] = 2;
		                count--;
		                queue.add(new int[]{r, c-1});
		            }
		            
		            // 右
		            if (c+1 < n && grid[r][c+1] == 1) {
		                grid[r][c+1] = 2;
		                count--;
		                queue.add(new int[]{r, c+1});
		            }
		        }
		}
		if(count > 0) {
			return -1 ;
		}else {
			return round ;
		}
	}
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值