2025年- H57-Lc165--994.腐烂的橘子(图论,广搜)--Java版 - 教程

1.题目描述

在这里插入图片描述

2.思路

在这里插入图片描述

3.代码实现

import java.util.LinkedList
;
import java.util.Queue
;
public
class H994 {
public
int orangesRotting(
int[][] grid) {
//1.获取行数
int rows=grid.length;
int cols=grid[0].length;
//2.创建队列用于bfs
Queue<
int[]> que=
new LinkedList<
>(
)
;
//3.记录新鲜橘子的数量
int fresh=0
;
//4.遍历整个网络,初始化队列
for(
int i=0
;i<rows;i++
)
{
for(
int j=0
;j<cols;j++
)
{
//如果是腐烂的橘子,加入队列中作为bfs的起点
if(grid[i][j]==2
)
{
//把腐烂橘子当前坐标加入到队列中
que.offer(
new
int[]{
i,j
}
)
;
}
//如果是新鲜橘子,统计数量
if(grid[i][j]==1
)
{
fresh++
;
}
}
}
//如果没有新鲜的橘子,直接返回0分钟
if(fresh==0
)
return 0
;
//定义方向数组,用于上下左右
int[][] dirs={
{
1
,0
}
,{
0
,1
}
,{
0
,-1
}
,{
-1
,0
}
}
;
int minutes=0
;
//记录分钟数
//bfs开始,因为que存储了腐烂的橘子的坐标
while(!que.isEmpty(
)
)
{
int size=que.size(
)
;
//这一分钟是否有橘子感染
boolean rotted=false
;
for(
int i=0
;i<size;i++
)
{
int[] pos=que.poll(
)
;
//删除队首元素,并返回队首元素的值
int x=pos[0]
;
int y=pos[1]
;
//遍历腐烂橘子的四个方向
//dirs是二维数组,也就是一维数组dir[]的一维数组
for(
int[] dir:dirs)
{
int nextx=x+dir[0]
;
int nexty=y+dir[1]
;
//如果在网格内且是新鲜橘子,将它变成腐烂橘子,并把新鲜橘子数-1
if(nextx>=0&&nextx<rows&&nexty>=0&&nexty<cols&&grid[nextx][nexty]==1
)
{
//变成腐烂橘子
grid[nextx][nexty]=2
;
//新鲜橘子数量减少
fresh--
;
//加入下一轮处理
que.offer(
new
int[]{
nextx,nexty
}
)
;
rotted=true
;
//防止腐烂的橘子重复计数
}
}
}
if(rotted==true
)
{
minutes++
;
}
}
if(fresh==0
)
{
return minutes;
}
else {
return -1
;
}
}
public
static
void main(String[] args)
{
int[][] grid={
{
2
,1
,1
}
,{
1
,1
,0
}
,{
0
,1
,1
}
}
;
H994 test=
new H994(
)
;
int result=test.orangesRotting(grid)
;
System.out.print(result)
;
}
}
posted on 2025-10-08 16:06  ljbguanli  阅读(8)  评论(0)    收藏  举报