-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathleetcode-994-rotting-Oranges.js
106 lines (89 loc) · 2.53 KB
/
leetcode-994-rotting-Oranges.js
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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
// function orangesRotting(grid) {
// const rotten = [];
// let hasFresh = false;
// let hasRotten = false;
// for (let i = 0; i < grid.length; i++) {
// for (let j = 0; j < grid[0].length; j++) {
// if (grid[i][j] === 1) hasFresh = true;
// if (grid[i][j] === 2) {
// hasRotten = true;
// rotten.push([i, j, 0]);
// }
// }
// }
// if (hasFresh && !hasRotten) return -1;
// if (!hasFresh) return 0;
// let maxTime = 0;
// const visited = new Set(rotten.map(([r, c]) => `${r},${c}`));
// while (rotten.length > 0) {
// const [y, x, time] = rotten.shift();
// maxTime = Math.max(maxTime, time);
// grid[y][x] = 2;
// const neighbors = [
// [y + 1, x],
// [y - 1, x],
// [y, x + 1],
// [y, x - 1],
// ];
// for (const [neiY, neiX] of neighbors) {
// const isInBounds =
// 0 <= neiY && neiY < grid.length && 0 <= neiX && neiX < grid[0].length;
// const neiYX = `${neiY},${neiX}`;
// if (isInBounds && grid[neiY][neiX] === 1 && !visited.has(neiYX)) {
// rotten.push([neiY, neiX, time + 1]);
// visited.add(neiYX);
// }
// }
// }
// for (const row of grid) {
// if (row.some((cell) => cell === 1)) return -1;
// }
// return maxTime;
// }
// CHAT GPT SOLUTION: without expensive .shift()
function orangesRotting(grid) {
const rows = grid.length;
const cols = grid[0].length;
const rottenQueue = [];
let freshOranges = 0;
for (let row = 0; row < rows; row++) {
for (let col = 0; col < cols; col++) {
if (grid[row][col] === 1) {
freshOranges++;
} else if (grid[row][col] === 2) {
rottenQueue.push([row, col]);
}
}
}
let minutes = 0;
const directions = [
[1, 0],
[-1, 0],
[0, 1],
[0, -1],
];
while (rottenQueue.length > 0 && freshOranges > 0) {
const newRottenQueue = [];
for (const [currentRow, currentCol] of rottenQueue) {
for (const [rowDir, colDir] of directions) {
const newRow = currentRow + rowDir;
const newCol = currentCol + colDir;
if (
newRow >= 0 &&
newRow < rows &&
newCol >= 0 &&
newCol < cols &&
grid[newRow][newCol] === 1
) {
grid[newRow][newCol] = 2;
freshOranges--;
newRottenQueue.push([newRow, newCol]);
}
}
}
rottenQueue.length = 0;
Array.prototype.push.apply(rottenQueue, newRottenQueue);
minutes++;
}
return freshOranges === 0 ? minutes : -1;
}