Simple breadth first search (BFS) problem : Store each batch of rotten oranges in a queue . Take out rotten oranges in batches , Take out the rotten orange and put in the fresh rotten orange at the same time .
import java.util.LinkedList; import java.util.Queue; class Solution { int[][]
dist= {{-1,0},{1,0},{0,1},{0,-1}};// Up, down, left and right public int orangesRotting(int[][]
grid) { int time = 0;// time 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){
// The first batch of rotten oranges is assigned as true, Prevent repeated traversal queue.offer(new int[]{i,j});// Rotten oranges join the queue booleans[i][j] =
true; } if(grid[i][j] == 0){// Empty cells are not processed , Prevent traversal set to true booleans[i][j] = true; } } }
int[] a = new int[2]; while(!queue.isEmpty()){ int num = queue.size();
// Number of rotten oranges in each batch int flag = 0;// If rotten oranges can infect fresh oranges, it will change flag Value of . 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++; } } // Traverse all cells , Return if there are fresh oranges -1, Otherwise, return time . for(int i = 0; i <
n;i++){ for(int j = 0;j < m;j++){ if(grid[i][j] == 1){ return -1; } } } return
time; } }

Technology
©2019-2020 Toolsou All rights reserved,
Solve in servlet The Chinese output in is a question mark C String function and character function in language MySQL management 35 A small coup optimization Java performance —— Concise article Seven sorting algorithms (java code ) use Ansible Batch deployment SSH Password free login to remote host according to excel generate create Build table SQL sentence Spring Source code series ( sixteen )Spring merge BeanDefinition Principle of Virtual machine installation Linux course What are the common exception classes ?