forked from AnasImloul/Leetcode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathRotting Oranges.js
64 lines (59 loc) · 1.99 KB
/
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
let convertAdjacentCellsToRotten = (grid, locations, rottenOranges) => {
let didConvertAny = false;
let newLocations = [];
for(let i=0;i<locations.length;i++){
let loci = locations[i][0]
let locj = locations[i][1]
if(loci+1 < grid.length && grid[loci+1][locj] === 1) {
grid[loci+1][locj] = 2;
newLocations.push([loci+1,locj])
didConvertAny = true;
rottenOranges++
}
if(loci-1 >= 0 && grid[loci-1][locj] === 1) {
grid[loci-1][locj] = 2;
newLocations.push([loci-1,locj])
didConvertAny = true;
rottenOranges++
}
if(locj+1 < grid[0].length && grid[loci][locj+1] === 1) {
grid[loci][locj+1] = 2;
newLocations.push([loci,locj+1])
didConvertAny = true;
rottenOranges++
}
if(locj-1 >= 0 && grid[loci][locj-1] === 1) {
grid[loci][locj-1] = 2;
newLocations.push([loci,locj-1])
didConvertAny = true;
rottenOranges++
}
}
return {didConvertAny:didConvertAny, rottenOranges,locations:[...newLocations]}
}
var orangesRotting = function(grid) {
let rottenLocation = [];
let rottenOranges = 0;
let totalOranges = 0;
let minutes = 0;
for(let i=0;i<grid.length;i++) {
for(let j=0;j<grid[0].length;j++) {
if(grid[i][j]===2) {
rottenLocation.push([i,j])
rottenOranges++;
}
if(grid[i][j]!==0) totalOranges++;
}
}
while (1) {
let gridConversionResult = convertAdjacentCellsToRotten(grid,rottenLocation,rottenOranges);
if (gridConversionResult.didConvertAny) {
rottenLocation = gridConversionResult.locations;
minutes++;
rottenOranges = gridConversionResult.rottenOranges;
}
else break
}
if(totalOranges===rottenOranges) return minutes;
else return -1
};