AlgoMaster Logo

Rotting Oranges

grid=[[2,1,1],[1,1,0],[0,1,1]]
1public int orangesRotting(int[][] grid) {
2    if (grid == null || grid.length == 0) {
3        return -1;
4    }
5
6    int rows = grid.length;
7    int cols = grid[0].length;
8    Queue<int[]> q = new LinkedList<>();
9    int fresh = 0;
10
11    // Initialize queue with all rotten oranges; count fresh
12    for (int r = 0; r < rows; r++) {
13        for (int c = 0; c < cols; c++) {
14            if (grid[r][c] == 2) {
15                q.offer(new int[]{r, c, 0});   // (row, col, minute)
16            } else if (grid[r][c] == 1) {
17                fresh++;
18            }
19        }
20    }
21
22    if (fresh == 0) {
23        return 0;
24    }
25
26    int[][] dirs = {{1,0}, {-1,0}, {0,1}, {0,-1}}; // Down, Up, Right, Left
27    int minutes = 0;
28
29    while (!q.isEmpty()) {
30        int[] curr = q.poll();
31        int r = curr[0], c = curr[1];
32        minutes = curr[2];
33        for (int[] dir : dirs) {
34            int nr = r + dir[0], nc = c + dir[1];
35            if (nr >= 0 && nr < rows && nc >= 0 && nc < cols && grid[nr][nc] == 1) {
36                grid[nr][nc] = 2;        // rot it
37                fresh--;
38                q.offer(new int[]{nr, nc, minutes + 1});
39            }
40        }
41    }
42
43    return fresh == 0 ? minutes : -1;
44}
0 / 45
211110011queueFreshRotten