|
1 | 1 | class Solution {
|
2 |
| - private static final int[][] DIRS = {{1, 0}, {0, 1}, {-1, 0}, {0, -1}}; |
3 |
| - |
| 2 | + private final int[][] DIRS = {{1, 0}, {0, 1}, {-1, 0}, {0, -1}}; |
| 3 | + |
4 | 4 | public int orangesRotting(int[][] grid) {
|
5 |
| - Queue<int[]> infectedOranges = new LinkedList<>(); |
6 |
| - int numOfFreshOranges = 0; |
7 |
| - for (int i = 0; i < grid.length; i++) { |
8 |
| - for (int j = 0; j < grid[i].length; j++) { |
| 5 | + Queue<int[]> queue = new LinkedList<>(); |
| 6 | + int nonRottenCount = 0; |
| 7 | + int numRows = grid.length; |
| 8 | + int numCols = grid[0].length; |
| 9 | + for (int i = 0; i < numRows; i++) { |
| 10 | + for (int j = 0; j < numCols; j++) { |
9 | 11 | if (grid[i][j] == 2) {
|
10 |
| - infectedOranges.add(new int[]{i, j}); |
| 12 | + queue.add(new int[]{i, j}); |
| 13 | + } else if (grid[i][j] == 1) { |
| 14 | + nonRottenCount++; |
11 | 15 | }
|
12 |
| - numOfFreshOranges += grid[i][j] == 1 ? 1 : 0; |
13 | 16 | }
|
14 | 17 | }
|
15 |
| - int numOfMinutes = 0; |
16 |
| - while (!infectedOranges.isEmpty()) { |
17 |
| - int infectedOrangeSize = infectedOranges.size(); |
18 |
| - boolean newInfected = false; |
19 |
| - while (infectedOrangeSize-- > 0) { |
20 |
| - int[] infectedOrangeCoordinate = infectedOranges.poll(); |
| 18 | + int totalTime = 0; |
| 19 | + while (!queue.isEmpty() && nonRottenCount > 0) { |
| 20 | + int size = queue.size(); |
| 21 | + while (size-- > 0) { |
| 22 | + int[] removed = queue.remove(); |
21 | 23 | for (int[] dir : DIRS) {
|
22 |
| - int newRowCoordinate = infectedOrangeCoordinate[0] + dir[0]; |
23 |
| - int newColCoordinate = infectedOrangeCoordinate[1] + dir[1]; |
24 |
| - if (isValidInfection(grid, newRowCoordinate, newColCoordinate)) { |
25 |
| - infectedOranges.add(new int[]{newRowCoordinate, newColCoordinate}); |
26 |
| - grid[newRowCoordinate][newColCoordinate] = 2; |
27 |
| - newInfected = true; |
28 |
| - numOfFreshOranges--; |
| 24 | + int newX = removed[0] + dir[0]; |
| 25 | + int newY = removed[1] + dir[1]; |
| 26 | + if (newX >= 0 && newY >= 0 && newX < numRows && newY < numCols && grid[newX][newY] == 1) { |
| 27 | + grid[newX][newY] = 2; |
| 28 | + nonRottenCount--; |
| 29 | + queue.add(new int[]{newX, newY}); |
29 | 30 | }
|
30 | 31 | }
|
31 | 32 | }
|
32 |
| - numOfMinutes += newInfected ? 1 : 0; |
| 33 | + totalTime++; |
33 | 34 | }
|
34 |
| - return numOfFreshOranges > 0 ? -1 : numOfMinutes; |
35 |
| - } |
36 |
| - |
37 |
| - private boolean isValidInfection(int[][] grid, int rowCoordinate, int colCoordinate) { |
38 |
| - return rowCoordinate >= 0 && colCoordinate >= 0 && rowCoordinate < grid.length |
39 |
| - && colCoordinate < grid[0].length && grid[rowCoordinate][colCoordinate] == 1; |
| 35 | + return nonRottenCount == 0 ? totalTime : -1; |
40 | 36 | }
|
41 | 37 | }
|
0 commit comments