1
let convertAdjacentCellsToRotten = (grid, locations, rottenOranges) => {
2
let didConvertAny = false;
3
let newLocations = [];
4
for (let i = 0; i < locations.length; i++) {
5
let loci = locations[i][0];
6
let locj = locations[i][1];
7

8
if (loci + 1 < grid.length && grid[loci + 1][locj] === 1) {
9
grid[loci + 1][locj] = 2;
10
newLocations.push([loci + 1, locj]);
11
didConvertAny = true;
12
rottenOranges++;
13
}
14
if (loci - 1 >= 0 && grid[loci - 1][locj] === 1) {
15
grid[loci - 1][locj] = 2;
16
newLocations.push([loci - 1, locj]);
17

18
didConvertAny = true;
19
rottenOranges++;
20
}
21
if (locj + 1 < grid[0].length && grid[loci][locj + 1] === 1) {
22
grid[loci][locj + 1] = 2;
23
newLocations.push([loci, locj + 1]);
24
didConvertAny = true;
25
rottenOranges++;
26
}
27
if (locj - 1 >= 0 && grid[loci][locj - 1] === 1) {
28
grid[loci][locj - 1] = 2;
29
newLocations.push([loci, locj - 1]);
30
didConvertAny = true;
31
rottenOranges++;
32
}
33
}
34

35
return {
36
didConvertAny: didConvertAny,
37
rottenOranges,
38
locations: [...newLocations],
39
};
40
};
41
var orangesRotting = function (grid) {
42
let rottenLocation = [];
43
let rottenOranges = 0;
44
let totalOranges = 0;
45
let minutes = 0;
46
for (let i = 0; i < grid.length; i++) {
47
for (let j = 0; j < grid[0].length; j++) {
48
if (grid[i][j] === 2) {
49
rottenLocation.push([i, j]);
50
rottenOranges++;
51
}
52
if (grid[i][j] !== 0) totalOranges++;
53
}
54
}
55

56
while (1) {
57
let gridConversionResult = convertAdjacentCellsToRotten(
58
grid,
59
rottenLocation,
60
rottenOranges
61
);
62
if (gridConversionResult.didConvertAny) {
63
rottenLocation = gridConversionResult.locations;
64
minutes++;
65
rottenOranges = gridConversionResult.rottenOranges;
66
} else break;
67
}
68
if (totalOranges === rottenOranges) return minutes;
69
else return -1;
70
};

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0