classSolution { publicintorangesRotting(int[][] grid) { if (grid == null || grid.length == 0) { return0; } introws= grid.length; intcols= grid[0].length; Queue<int[]> queue = newLinkedList<>(); intcountFresh=0; //Put the position of all rotten oranges in queue //count the number of fresh oranges for (inti=0; i < rows; i++) { for (intj=0; j < cols; j++) { if (grid[i][j] == 2) { queue.offer(newint[]{i, j}); } elseif (grid[i][j] == 1) { countFresh++; } } } //if count of fresh oranges is zero --> return 0 if (countFresh == 0) { return0; } intcount=0; int[][] steps = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}}; //bfs starting from initially rotten oranges while (!queue.isEmpty()) { ++count; intsize= queue.size(); for (inti=0; i < size; i++) { int[] elementCoordinate = queue.poll(); for (int[] step : steps) { intx= elementCoordinate[0] + step[0]; inty= elementCoordinate[1] + step[1]; //if x or y is out of bound //or the orange at (x , y) is already rotten //or the cell at (x , y) is empty //we do nothing if (x < 0 || y < 0 || x >= rows || y >= cols || grid[x][y] == 0 || grid[x][y] == 2) { continue; } //mark the orange at (x , y) as rotten grid[x][y] = 2; //put the new rotten orange at (x , y) in queue queue.offer(newint[]{x, y}); //decrease the count of fresh oranges by 1 countFresh--; } } } return countFresh == 0 ? count - 1 : -1; } }