当前位置:网站首页>力扣994:腐烂的橘子(BFS)
力扣994:腐烂的橘子(BFS)
2022-07-29 05:09:00 【小洪正在努力】

简单的广度优先搜索(BFS)问题:用队列存储每批腐烂的橘子。按批次取出腐烂的橘子,取出腐烂橘子的同时放入由新鲜变腐烂的橘子。
import java.util.LinkedList;
import java.util.Queue;
class Solution {
int[][] dist = {
{
-1,0},{
1,0},{
0,1},{
0,-1}};//上下左右四个方向
public int orangesRotting(int[][] grid) {
int time = 0;//计时
Queue<int[]> queue = new LinkedList<int[]>();
int n = grid.length;
int m = grid[0].length;
boolean[][] booleans = new boolean[n][m];
for(int i = 0;i < n;i++){
for(int j = 0;j < m;j++){
if(grid[i][j] == 2){
//首批腐烂的橘子赋值为true,防止重复遍历
queue.offer(new int[]{
i,j});//腐烂的橘子加入队列
booleans[i][j] = true;
}
if(grid[i][j] == 0){
//空单元格不做处理,防止遍历设值为true
booleans[i][j] = true;
}
}
}
int[] a = new int[2];
while(!queue.isEmpty()){
int num = queue.size();//每批腐烂橘子的个数
int flag = 0;//若腐烂橘子能感染新鲜的橘子就改变flag的值。
for(int number = 0;number < num;number++){
a = queue.poll();
for(int i = 0;i < 4;i++){
int x = a[0] + dist[i][0];
int y = a[1] + dist[i][1];
if(x>=0&&y>=0&&x<n&&y<m&&booleans[x][y]!=true){
grid[x][y] = 2;
queue.offer(new int[]{
x,y});
booleans[x][y] = true;
flag = 1;
}
}
}
if(flag == 1){
time++;
}
}
//遍历所有单元格,若存在新鲜橘子则返回-1,否则返回时间。
for(int i = 0; i < n;i++){
for(int j = 0;j < m;j++){
if(grid[i][j] == 1){
return -1;
}
}
}
return time;
}
}
边栏推荐
猜你喜欢

哈夫曼树以及哈夫曼编码在文件压缩上的应用

Li Yan, CEO of parallel cloud: cloudxr, opens the channel to the metauniverse

刷题狂魔—LeetCode之剑指offer58 - II. 左旋转字符串 详解

阿里云架构师细说游戏行业九大趋势

串口通讯部分详解

Day 5

Xiaobai high salary shortcut Qt development game Snake

【C语言系列】— 一道递归小题目

C语言 一级指针

365 day challenge leetcode 1000 questions - day 040 design jump table + avoid flooding + find the latest grouping with size M + color ball with reduced sales value
随机推荐
Day 5
Alibaba cloud Zhang Xintao: heterogeneous computing provides surging power for the digital economy
CMU15-213 Malloc Lab实验记录
2022数学建模竞赛暑期培训讲座——最优化方法:目标规划
Cryengine Technology
法线可视化
Best practices of JD cloud Distributed Link Tracking in financial scenarios
C语言 一级指针
OCCT学习002-----环境搭建
Alibaba cloud and Dingjie software released the cloud digital factory solution to realize the localized deployment of cloud MES system
R & D efficiency | analysis of kubernetes' core technology and Devops' landing experience
Live broadcast preview | how to save 30% labor cost and shorten 80% trademark processing cycle?
Alibaba cloud architect Liang Xu: MES on cloud box helps customers quickly build digital factories
[event preview] cloud development, efficient and intelligent - the second Alibaba cloud ECS cloudbuild developer competition is about to start
C语言 N皇后问题
C语言 一维数组
【C语言系列】— 字符串+部分转义字符详解+注释小技巧
JD cloud golden autumn cloud special offer is in progress! Code scanning participation activities
适创科技以云仿真平台,支持“中国智造”升级
QML control: combobox