-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path0994-rotting-oranges.js
More file actions
63 lines (57 loc) · 1.61 KB
/
0994-rotting-oranges.js
File metadata and controls
63 lines (57 loc) · 1.61 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
/**
* Rotting Oranges
* Time Complexity: O(R * C)
* Space Complexity: O(R * C)
*/
var orangesRotting = function (grid) {
const gridRows = grid.length;
const gridCols = grid[0].length;
const rottenOrangesQueue = [];
let totalFreshOranges = 0;
let elapsedMinutes = 0;
for (let rowIndex = 0; rowIndex < gridRows; rowIndex++) {
for (let colIndex = 0; colIndex < gridCols; colIndex++) {
if (grid[rowIndex][colIndex] === 2) {
rottenOrangesQueue.push([rowIndex, colIndex, 0]);
} else if (grid[rowIndex][colIndex] === 1) {
totalFreshOranges++;
}
}
}
const adjacentDirections = [
[-1, 0],
[1, 0],
[0, -1],
[0, 1],
];
while (rottenOrangesQueue.length > 0) {
const [currentOrangeRow, currentOrangeCol, currentTimePoint] =
rottenOrangesQueue.shift();
elapsedMinutes = Math.max(elapsedMinutes, currentTimePoint);
for (const [rowChange, colChange] of adjacentDirections) {
const nextOrangeRow = currentOrangeRow + rowChange;
const nextOrangeCol = currentOrangeCol + colChange;
const minuteIncrement = currentTimePoint + 1;
if (
nextOrangeRow >= 0 &&
nextOrangeRow < gridRows &&
nextOrangeCol >= 0 &&
nextOrangeCol < gridCols &&
grid[nextOrangeRow][nextOrangeCol] === 1
) {
grid[nextOrangeRow][nextOrangeCol] = 2;
totalFreshOranges--;
rottenOrangesQueue.push([
nextOrangeRow,
nextOrangeCol,
minuteIncrement,
]);
}
}
}
if (totalFreshOranges > 0) {
return -1;
} else {
return elapsedMinutes;
}
};