https://leetcode.com/problems/rotting-oranges/
- Queue
- BFS
Run multi-source BFS from all rotten oranges and spread the rot level by level.
O(m * n)
O(m * n)
import java.util.*;
class Solution {
public int orangesRotting(int[][] grid) {
int rows = grid.length, cols = grid[0].length, fresh = 0, minutes = 0;
Queue<int[]> queue = new LinkedList<>();
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
if (grid[i][j] == 2) queue.offer(new int[]{i, j});
if (grid[i][j] == 1) fresh++;
}
}
int[][] dirs = {{1,0},{-1,0},{0,1},{0,-1}};
while (!queue.isEmpty() && fresh > 0) {
int size = queue.size();
minutes++;
for (int s = 0; s < size; s++) {
int[] curr = queue.poll();
for (int[] d : dirs) {
int r = curr[0] + d[0], c = curr[1] + d[1];
if (r >= 0 && c >= 0 && r < rows && c < cols && grid[r][c] == 1) {
grid[r][c] = 2;
fresh--;
queue.offer(new int[]{r, c});
}
}
}
}
return fresh == 0 ? minutes : -1;
}
}