Skip to content

Commit aa80afc

Browse files
authored
Update Rotting Oranges.java
1 parent 65fcb29 commit aa80afc

File tree

1 file changed

+24
-28
lines changed

1 file changed

+24
-28
lines changed

Medium/Rotting Oranges.java

Lines changed: 24 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -1,41 +1,37 @@
11
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+
44
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++) {
911
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++;
1115
}
12-
numOfFreshOranges += grid[i][j] == 1 ? 1 : 0;
1316
}
1417
}
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();
2123
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});
2930
}
3031
}
3132
}
32-
numOfMinutes += newInfected ? 1 : 0;
33+
totalTime++;
3334
}
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;
4036
}
4137
}

0 commit comments

Comments
 (0)