forked from neetcode-gh/leetcode
- Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path0994-rotting-oranges.ts
49 lines (43 loc) · 1.18 KB
/
0994-rotting-oranges.ts
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
functionorangesRotting(grid: number[][]): number{
let[ROWS,COLS,time,fresh,q]=[grid.length,grid[0].length,0,0,[]];
letdirs=[
[0,1],
[0,-1],
[1,0],
[-1,0],
];
// count fresh oranges and add rotten oranges to queue
for(leti=0;i<ROWS;i++){
for(letj=0;j<COLS;j++){
if(grid[i][j]===1){
fresh++;
}
if(grid[i][j]===2){
q.push([i,j]);
}
}
}
while(q.length>0&&fresh>0){
letqLen=q.length;
for(letrot=0;rot<qLen;rot++){
let[row,col]=q.shift();
for(letdirofdirs){
let[r,c]=[row+dir[0],col+dir[1]];
if(
r<0||
r>=ROWS||
c<0||
c>=COLS||
grid[r][c]!==1
){
continue;
}
grid[r][c]=2;
fresh--;
q.push([r,c]);
}
}
time++;
}
returnfresh>0 ? -1 : time;
}