Skip to content

Commit 17ec001

Browse files
committed
Add solution #994
1 parent 3adb56b commit 17ec001

File tree

2 files changed

+51
-0
lines changed

2 files changed

+51
-0
lines changed

README.md

+1
Original file line numberDiff line numberDiff line change
@@ -164,6 +164,7 @@
164164
977|[Squares of a Sorted Array](./0977-squares-of-a-sorted-array.js)|Easy|
165165
985|[Sum of Even Numbers After Queries](./0985-sum-of-even-numbers-after-queries.js)|Easy|
166166
989|[Add to Array-Form of Integer](./0989-add-to-array-form-of-integer.js)|Easy|
167+
994|[Rotting Oranges](./0994-rotting-oranges.js)|Medium|
167168
997|[Find the Town Judge](./0997-find-the-town-judge.js)|Easy|
168169
1009|[Complement of Base 10 Integer](./1009-complement-of-base-10-integer.js)|Easy|
169170
1010|[Pairs of Songs With Total Durations Divisible by 60](./1010-pairs-of-songs-with-total-durations-divisible-by-60.js)|Medium|

solutions/0994-rotting-oranges.js

+50
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
/**
2+
* 994. Rotting Oranges
3+
* https://leetcode.com/problems/rotting-oranges/
4+
* Difficulty: Medium
5+
*
6+
* You are given an m x n grid where each cell can have one of three values:
7+
* - 0 representing an empty cell,
8+
* - 1 representing a fresh orange, or
9+
* - 2 representing a rotten orange.
10+
*
11+
* Every minute, any fresh orange that is 4-directionally adjacent to a rotten
12+
* orange becomes rotten.
13+
*
14+
* Return the minimum number of minutes that must elapse until no cell has a
15+
* fresh orange. If this is impossible, return -1.
16+
*/
17+
18+
/**
19+
* @param {number[][]} grid
20+
* @return {number}
21+
*/
22+
var orangesRotting = function(grid) {
23+
const queue = [];
24+
let count = 0;
25+
26+
for (let i = 0; i < grid.length; i++) {
27+
for (let j = 0; j < grid[0].length; j++) {
28+
if (grid[i][j] === 2) {
29+
queue.push([i, j, 0]);
30+
}
31+
}
32+
}
33+
34+
while (queue.length) {
35+
const [i, j, k] = queue.shift();
36+
[[-1, 0], [1, 0], [0, -1], [0, 1]].forEach(p => {
37+
const [x, y, z] = [i + p[0], j + p[1], k + 1];
38+
if (x > -1 && x < grid.length && y > -1 && y < grid[0].length) {
39+
if (grid[x][y] === 1) {
40+
grid[x][y] = 2;
41+
count = Math.max(count, z);
42+
queue.push([x, y, z]);
43+
}
44+
}
45+
});
46+
}
47+
48+
const isIncomplete = grid.some(row => row.some(n => n === 1));
49+
return isIncomplete ? -1 : count;
50+
};

0 commit comments

Comments
 (0)