|
| 1 | +functionorangesRotting(grid){ |
| 2 | +constrows=grid.length; |
| 3 | +constcols=grid[0].length; |
| 4 | +letqueue=[]; |
| 5 | +letfreshOranges=0; |
| 6 | + |
| 7 | +// Initialize the queue with all rotten oranges and count fresh oranges |
| 8 | +for(letr=0;r<rows;r++){ |
| 9 | +for(letc=0;c<cols;c++){ |
| 10 | +if(grid[r][c]===2){ |
| 11 | +queue.push([r,c]); |
| 12 | +}elseif(grid[r][c]===1){ |
| 13 | +freshOranges++; |
| 14 | +} |
| 15 | +} |
| 16 | +} |
| 17 | + |
| 18 | +// If there are no fresh oranges, return 0 |
| 19 | +if(freshOranges===0)return0; |
| 20 | + |
| 21 | +letminutes=0; |
| 22 | +constdirections=[ |
| 23 | +[0,1],// right |
| 24 | +[1,0],// down |
| 25 | +[0,-1],// left |
| 26 | +[-1,0]// up |
| 27 | +]; |
| 28 | + |
| 29 | +// Step 2: Perform BFS |
| 30 | +while(queue.length>0){ |
| 31 | +letsize=queue.length; |
| 32 | +letnewRotten=false; |
| 33 | + |
| 34 | +for(leti=0;i<size;i++){ |
| 35 | +let[x,y]=queue.shift(); |
| 36 | + |
| 37 | +for(let[dx,dy]ofdirections){ |
| 38 | +letnx=x+dx; |
| 39 | +letny=y+dy; |
| 40 | + |
| 41 | +// Check if the neighboring cell is a fresh orange |
| 42 | +if(nx>=0&&ny>=0&&nx<rows&&ny<cols&&grid[nx][ny]===1){ |
| 43 | +grid[nx][ny]=2;// Make it rotten |
| 44 | +freshOranges--;// Decrease count of fresh oranges |
| 45 | +queue.push([nx,ny]);// Add it to the queue |
| 46 | +newRotten=true; |
| 47 | +} |
| 48 | +} |
| 49 | +} |
| 50 | + |
| 51 | +// If rotten oranges exist, increment minutes |
| 52 | +if(newRotten)minutes++; |
| 53 | +} |
| 54 | + |
| 55 | +// Check if there are any fresh oranges left |
| 56 | +returnfreshOranges===0 ?minutes :-1; |
| 57 | +} |