Given a matrix mat[][], where each cell in the matrix can have values 0, 1 or 2 which has the following meaning:
0: Empty cell
1: Cells have fresh oranges
2: Cells have rotten oranges
Find the minimum time required so that all the oranges become rotten. A rotten orange at index (i,j) can rot other fresh oranges which are its neighbours (up, down, left, and right). Each rotten orange takes 1 unit of time to rot all its adjacent fresh oranges.
Note : If it is impossible to rot every orange then simply return -1.
[Naive Approach] - Using Iteration - O((n x m) ^ 2) Time and O(1) Space
We know that at each time unit, every rotten orange (2) can rot its adjacent fresh oranges (1). So, we start by traversing the matrix and at time = 0, for every rotten orange, we rot its adjacent fresh oranges. However, we must ensure that freshly rotted oranges do not rot others within the same time unit, otherwise it will cause incorrect overlapping updates.
To handle this properly: Whenever a rotten orange at cell (i, j) rots a fresh orange, we update that fresh orange’s value to mat[i][j] + 1. This way, oranges that become rotten at time t will have a value t + 2, meaning at the next time step (t + 1), they can start infecting their neighbors. This process continues as long as at least one fresh orange is rotted in a given iteration.The moment no more oranges can be rotted, the last time value we used indicates the minimum time required to rot all oranges. Finally, we perform a check to see if any fresh oranges (1s) are still left in the grid:
If yes - it means not all oranges could rot, so we return -1.
Otherwise - return the last computed time as the result.
C++
//Driver Code Starts#include<iostream>#include<vector>usingnamespacestd;//Driver Code EndsboolisSafe(inti,intj,intn,intm){return0<=i&&i<n&&0<=j&&j<m;}intorangesRot(vector<vector<int>>&mat){intn=mat.size();intm=mat[0].size();// to check if any changes are madeboolchanged;// counter of elapsed timeintelapsedTime=0;// all four directionsvector<vector<int>>directions={{1,0},{0,1},{-1,0},{0,-1}};// iterate until changes are therewhile(true){changed=false;for(inti=0;i<n;i++){for(intj=0;j<m;j++){// check if the cell was marked in last iterationif(mat[i][j]==elapsedTime+2){// change 4-directionally connected cellsfor(auto&dir:directions){intx=i+dir[0];inty=j+dir[1];// if cell is in the matrix and the//orange is freshif(isSafe(x,y,n,m)&&mat[x][y]==1){mat[x][y]=mat[i][j]+1;changed=true;}}}}}// if no changes are doneif(!changed){break;}elapsedTime++;}for(inti=0;i<n;i++){for(intj=0;j<m;j++){// if any orange is found not rotten, return -1if(mat[i][j]==1){return-1;}}}returnelapsedTime;}//Driver Code Startsintmain(){vector<vector<int>>mat={{2,1,0,2,1},{1,0,1,2,1},{1,0,0,2,1}};cout<<orangesRot(mat)<<endl;return0;}//Driver Code Ends
Java
//Driver Code StartspublicclassGfG{//Driver Code EndsprivatebooleanisSafe(inti,intj,intn,intm){return0<=i&&i<n&&0<=j&&j<m;}publicintorangesRot(int[][]mat){intn=mat.length;intm=mat[0].length;// to check if any changes are madebooleanchanged;// counter of elapsed timeintelapsedTime=0;// all four directionsint[][]directions={{1,0},{0,1},{-1,0},{0,-1}};// iterate until changes are therewhile(true){changed=false;for(inti=0;i<n;i++){for(intj=0;j<m;j++){// check if the cell was marked in last iterationif(mat[i][j]==elapsedTime+2){// change 4-directionally connected cellsfor(int[]dir:directions){intx=i+dir[0];inty=j+dir[1];// if cell is in the matrix and the//orange is freshif(isSafe(x,y,n,m)&&mat[x][y]==1){mat[x][y]=mat[i][j]+1;changed=true;}}}}}// if no changes are doneif(!changed){break;}elapsedTime++;}for(inti=0;i<n;i++){for(intj=0;j<m;j++){// if any orange is found not rotten, return -1if(mat[i][j]==1){return-1;}}}returnelapsedTime;}//Driver Code Startspublicstaticvoidmain(String[]args){int[][]mat={{2,1,0,2,1},{1,0,1,2,1},{1,0,0,2,1}};GfGsol=newGfG();System.out.println(sol.orangesRot(mat));}}//Driver Code Ends
Python
defisSafe(i,j,n,m):return0<=i<nand0<=j<mdeforangesRot(mat):n=len(mat)m=len(mat[0])# to check if any changes are madechanged=False# counter of elapsed timeelapsedTime=0# all four directionsdirections=[[1,0],[0,1],[-1,0],[0,-1]]# iterate until changes are therewhileTrue:foriinrange(n):forjinrange(m):# check if the cell was marked in last iterationifmat[i][j]==elapsedTime+2:# change 4-directionally connected cellsfordirindirections:x=i+dir[0]y=j+dir[1]# if cell is in the matrix and# the orange is freshifisSafe(x,y,n,m)andmat[x][y]==1:mat[x][y]=mat[i][j]+1changed=True# if no changes are doneifnotchanged:breakchanged=FalseelapsedTime+=1foriinrange(n):forjinrange(m):# if any orange is found# not rotten, return -1ifmat[i][j]==1:return-1returnelapsedTime#Driver Code Startsif__name__=="__main__":mat=[[2,1,0,2,1],[1,0,1,2,1],[1,0,0,2,1]]print(orangesRot(mat))#Driver Code Ends
C#
//Driver Code StartsusingSystem;usingSystem.Collections.Generic;classGfG{//Driver Code EndsstaticboolisSafe(inti,intj,intn,intm){return(i>=0&&i<n&&j>=0&&j<m);}staticintorangesRot(int[,]mat){intn=mat.GetLength(0);intm=mat.GetLength(1);// to check if any changes are madeboolchanged=false;// counter of elapsed timeintelapsedTime=0;// all four directionsint[,]directions=newint[,]{{1,0},{0,1},{-1,0},{0,-1}};// iterate until changes are therewhile(true){for(inti=0;i<n;i++){for(intj=0;j<m;j++){// check if the cell was marked in last iterationif(mat[i,j]==elapsedTime+2){// change 4-directionally connected cellsfor(intd=0;d<4;d++){intx=i+directions[d,0];inty=j+directions[d,1];// if cell is in the matrix and// the orange is freshif(isSafe(x,y,n,m)&&mat[x,y]==1){mat[x,y]=mat[i,j]+1;changed=true;}}}}}// if no changes are doneif(!changed)break;changed=false;elapsedTime++;}for(inti=0;i<n;i++){for(intj=0;j<m;j++){// if any orange is found// not rotten, return -1if(mat[i,j]==1)return-1;}}returnelapsedTime;}//Driver Code StartsstaticvoidMain(string[]args){int[,]mat={{2,1,0,2,1},{1,0,1,2,1},{1,0,0,2,1}};Console.WriteLine(orangesRot(mat));}}//Driver Code Ends
JavaScript
functionisSafe(i,j,n,m){returni>=0&&i<n&&j>=0&&j<m;}functionorangesRot(mat){letn=mat.length;letm=mat[0].length;// to check if any changes are madeletchanged=false;// counter of elapsed timeletelapsedTime=0;// all four directionsconstdirections=[[1,0],[0,1],[-1,0],[0,-1]];// iterate until changes are therewhile(true){for(leti=0;i<n;i++){for(letj=0;j<m;j++){// check if the cell was marked in last iterationif(mat[i][j]===elapsedTime+2){// change 4-directionally connected cellsfor(constdirofdirections){letx=i+dir[0];lety=j+dir[1];// if cell is in the matrix and// the orange is freshif(isSafe(x,y,n,m)&&mat[x][y]===1){mat[x][y]=mat[i][j]+1;changed=true;}}}}}// if no changes are doneif(!changed)break;changed=false;elapsedTime++;}for(leti=0;i<n;i++){for(letj=0;j<m;j++){// if any orange is found// not rotten, return -1if(mat[i][j]===1)return-1;}}returnelapsedTime;}//Driver Code Starts// Driver Codeconstmat=[[2,1,0,2,1],[1,0,1,2,1],[1,0,0,2,1]];console.log(orangesRot(mat));//Driver Code Ends
Output
2
[Better Approach] - Using Depth First Search - O(n x m) Time and O(1) Space
The idea is to use DFS (Depth-First Search) because DFS explores deeply in one direction before backtracking. This property helps us simulate how the rot spreads from one orange to another over time.
We start by iterating through the entire matrix, and whenever we find a rotten orange (2), we begin a DFS from that cell. During the DFS, we go to all its adjacent cells and record the time when each orange becomes rotten. If a neighboring cell contains a fresh orange (1), that means it can now become rotten, so we recursively call DFS for that cell with the time current_time + 1. If a cell was already rotten earlier but now can rot in less time, we update its time and continue DFS from that cell again.
In this way, DFS helps us spread the rot recursively throughout the grid while keeping track of the minimum time taken for each orange to rot. After all DFS calls are complete, we iterate through the entire matrix once again.If we find any fresh orange still left, it means it was unreachable, so we return -1. Otherwise, we take the maximum recorded time — which represents the minimum time required to rot all the oranges.
C++
//Driver Code Starts#include<iostream>#include<vector>usingnamespacestd;//Driver Code EndsboolisSafe(inti,intj,intn,intm){return(i>=0&&i<n&&j>=0&&j<m);}// function to perform dfs and find fresh orangevoiddfs(vector<vector<int>>&mat,inti,intj,inttime){intn=mat.size();intm=mat[0].size();// update minimum timemat[i][j]=time;// all four directionsvector<vector<int>>directions={{1,0},{0,1},{-1,0},{0,-1}};// change 4-directionally connected cellsfor(autodir:directions){intx=i+dir[0];inty=j+dir[1];// if cell is in the matrix and// the orange is freshif(isSafe(x,y,n,m)&&(mat[x][y]==1||mat[x][y]>time+1)){dfs(mat,x,y,time+1);}}}intorangesRot(vector<vector<int>>&mat){intn=mat.size();intm=mat[0].size();// counter of elapsed timeintelapsedTime=0;// iterate through all the cellsfor(inti=0;i<n;i++){for(intj=0;j<m;j++){// if orange is initiall rottenif(mat[i][j]==2){dfs(mat,i,j,2);}}}// iterate through all the cellsfor(inti=0;i<n;i++){for(intj=0;j<m;j++){// if orange is freshif(mat[i][j]==1)return-1;// update the maximum timeelapsedTime=max(elapsedTime,mat[i][j]-2);}}returnelapsedTime;}//Driver Code Startsintmain(){vector<vector<int>>mat={{2,1,0,2,1},{1,0,1,2,1},{1,0,0,2,1}};cout<<orangesRot(mat);return0;}//Driver Code Ends
Java
//Driver Code StartsclassGfG{//Driver Code EndsstaticbooleanisSafe(inti,intj,intn,intm){return(i>=0&&i<n&&j>=0&&j<m);}// function to perform dfs and find fresh orangestaticvoiddfs(int[][]mat,inti,intj,inttime){intn=mat.length;intm=mat[0].length;// update minimum timemat[i][j]=time;// all four directionsint[][]directions={{1,0},{0,1},{-1,0},{0,-1}};// change 4-directionally connected cellsfor(int[]dir:directions){intx=i+dir[0];inty=j+dir[1];// if cell is in the matrix and// the orange is freshif(isSafe(x,y,n,m)&&(mat[x][y]==1||mat[x][y]>time+1)){dfs(mat,x,y,time+1);}}}staticintorangesRot(int[][]mat){intn=mat.length;intm=mat[0].length;// counter of elapsed timeintelapsedTime=0;// iterate through all the cellsfor(inti=0;i<n;i++){for(intj=0;j<m;j++){// if orange is initially rottenif(mat[i][j]==2){dfs(mat,i,j,2);}}}// iterate through all the cellsfor(inti=0;i<n;i++){for(intj=0;j<m;j++){// if orange is freshif(mat[i][j]==1)return-1;// update the maximum timeelapsedTime=Math.max(elapsedTime,mat[i][j]-2);}}returnelapsedTime;}//Driver Code Startspublicstaticvoidmain(String[]args){int[][]mat={{2,1,0,2,1},{1,0,1,2,1},{1,0,0,2,1}};System.out.println(orangesRot(mat));}}//Driver Code Ends
Python
defisSafe(i,j,n,m):return0<=i<nand0<=j<m# function to perform dfs and find fresh orangedefdfs(mat,i,j,time):n=len(mat)m=len(mat[0])# update minimum timemat[i][j]=time# all four directionsdirections=[[1,0],[0,1],[-1,0],[0,-1]]# change 4-directionally connected cellsfordirindirections:x=i+dir[0]y=j+dir[1]# if cell is in the matrix and# the orange is freshifisSafe(x,y,n,m)and(mat[x][y]==1ormat[x][y]>time+1):dfs(mat,x,y,time+1)deforangesRot(mat):n=len(mat)m=len(mat[0])# counter of elapsed timeelapsedTime=0# iterate through all the cellsforiinrange(n):forjinrange(m):# if orange is initially rottenifmat[i][j]==2:dfs(mat,i,j,2)# iterate through all the cellsforiinrange(n):forjinrange(m):# if orange is freshifmat[i][j]==1:return-1# update the maximum timeelapsedTime=max(elapsedTime,mat[i][j]-2)returnelapsedTime#Driver Code Startsif__name__=="__main__":mat=[[2,1,0,2,1],[1,0,1,2,1],[1,0,0,2,1]]print(orangesRot(mat))#Driver Code Ends
C#
//Driver Code StartsusingSystem;classGfG{//Driver Code EndsstaticboolisSafe(inti,intj,intn,intm){return(i>=0&&i<n&&j>=0&&j<m);}// function to perform dfs and find fresh orangestaticvoiddfs(int[,]mat,inti,intj,inttime){intn=mat.GetLength(0);intm=mat.GetLength(1);// update minimum timemat[i,j]=time;// all four directionsint[,]directions={{1,0},{0,1},{-1,0},{0,-1}};// change 4-directionally connected cellsfor(intd=0;d<4;d++){intx=i+directions[d,0];inty=j+directions[d,1];// if cell is in the matrix and// the orange is freshif(isSafe(x,y,n,m)&&(mat[x,y]==1||mat[x,y]>time+1)){dfs(mat,x,y,time+1);}}}staticintorangesRot(int[,]mat){intn=mat.GetLength(0);intm=mat.GetLength(1);// counter of elapsed timeintelapsedTime=0;// iterate through all the cellsfor(inti=0;i<n;i++){for(intj=0;j<m;j++){// if orange is initially rottenif(mat[i,j]==2){dfs(mat,i,j,2);}}}// iterate through all the cellsfor(inti=0;i<n;i++){for(intj=0;j<m;j++){// if orange is freshif(mat[i,j]==1)return-1;// update the maximum timeelapsedTime=Math.Max(elapsedTime,mat[i,j]-2);}}returnelapsedTime;}//Driver Code StartsstaticvoidMain(string[]args){int[,]mat={{2,1,0,2,1},{1,0,1,2,1},{1,0,0,2,1}};Console.WriteLine(orangesRot(mat));}}//Driver Code Ends
JavaScript
functionisSafe(i,j,n,m){returni>=0&&i<n&&j>=0&&j<m;}// function to perform dfs and find fresh orangefunctiondfs(mat,i,j,time){constn=mat.length;constm=mat[0].length;// update minimum timemat[i][j]=time;// all four directionsconstdirections=[[1,0],[0,1],[-1,0],[0,-1]];// change 4-directionally connected cellsfor(constdirofdirections){constx=i+dir[0];consty=j+dir[1];// if cell is in the matrix and// the orange is freshif(isSafe(x,y,n,m)&&(mat[x][y]===1||mat[x][y]>time+1)){dfs(mat,x,y,time+1);}}}functionorangesRot(mat){constn=mat.length;constm=mat[0].length;// counter of elapsed timeletelapsedTime=0;// iterate through all the cellsfor(leti=0;i<n;i++){for(letj=0;j<m;j++){// if orange is initially rottenif(mat[i][j]===2){dfs(mat,i,j,2);}}}// iterate through all the cellsfor(leti=0;i<n;i++){for(letj=0;j<m;j++){// if orange is freshif(mat[i][j]===1)return-1;// update the maximum timeelapsedTime=Math.max(elapsedTime,mat[i][j]-2);}}returnelapsedTime;}//Driver Code Starts// Driver Codeconstmat=[[2,1,0,2,1],[1,0,1,2,1],[1,0,0,2,1]];console.log(orangesRot(mat));//Driver Code Ends
Output
2
[Expected Approach] - Using Breadth First Search - O(n x m) Time and O(n x m) Space
The idea is to use BFS (Breadth-First Search) because BFS explores the grid level by level. In DFS, we can not say that a fresh orange getting rotten from another rotten orange represents its minimum time to rot because DFS explores deeply in one direction. However, in BFS ensuring that when a fresh orange becomes rotten, it is always at the earliest possible time.
To apply this idea, we first add all the initially rotten oranges to a queue. Then, we process them one by one from the queue. For each rotten orange, we check its four neighboring cells. If a neighbor is a fresh orange (1), it becomes rotten, and we push it into the queue. As BFS moves level by level, we also keep track of a variable to record the time taken — this value increases with each level processed. Once the queue becomes empty, it means all possible oranges have been processed. Finally, we check the grid again — if any fresh orange is still left, it means it couldn’t be reached, so we return -1. Otherwise, the maximum time recorded gives us the minimum time required to rot all the oranges.
Illustration:
C++
//Driver Code Starts#include<iostream>#include<vector>#include<queue>usingnamespacestd;//Driver Code EndsboolisSafe(inti,intj,intn,intm){return(i>=0&&i<n&&j>=0&&j<m);}// function to perform bfs and find minimum timeintorangesRot(vector<vector<int>>&mat){intn=mat.size();intm=mat[0].size();// queue to store coordinates of rotten orangesqueue<pair<int,int>>q;// counter of elapsed timeintelapsedTime=0;// push all initially rotten oranges into queuefor(inti=0;i<n;i++){for(intj=0;j<m;j++){if(mat[i][j]==2){q.push({i,j});}}}// directions for all four adjacent cellsvector<vector<int>>directions={{1,0},{0,1},{-1,0},{0,-1}};// perform BFSwhile(!q.empty()){intsize=q.size();boolflag=false;// process all oranges at current time levelfor(inti=0;i<size;i++){auto[x,y]=q.front();q.pop();// check all four directionsfor(autodir:directions){intnx=x+dir[0];intny=y+dir[1];// if cell is safe and has fresh orangeif(isSafe(nx,ny,n,m)&&mat[nx][ny]==1){// rot the orangemat[nx][ny]=2;q.push({nx,ny});flag=true;}}}// if at least one orange got rotten, increase the timeif(flag)elapsedTime++;}// check if any fresh orange still remainsfor(inti=0;i<n;i++){for(intj=0;j<m;j++){if(mat[i][j]==1)return-1;}}returnelapsedTime;}//Driver Code Startsintmain(){vector<vector<int>>mat={{2,1,0,2,1},{1,0,1,2,1},{1,0,0,2,1}};cout<<orangesRot(mat);return0;}//Driver Code Ends
Java
//Driver Code Startsimportjava.util.Arrays;importjava.util.Queue;importjava.util.LinkedList;classGFG{//Driver Code EndsstaticbooleanisSafe(inti,intj,intn,intm){return(i>=0&&i<n&&j>=0&&j<m);}// function to perform bfs and find minimum timestaticintorangesRot(int[][]mat){intn=mat.length;intm=mat[0].length;// queue to store coordinates of rotten orangesQueue<int[]>q=newLinkedList<>();// counter of elapsed timeintelapsedTime=0;// push all initially rotten oranges into queuefor(inti=0;i<n;i++){for(intj=0;j<m;j++){if(mat[i][j]==2){q.add(newint[]{i,j});}}}// directions for all four adjacent cellsint[][]directions={{1,0},{0,1},{-1,0},{0,-1}};// perform BFSwhile(!q.isEmpty()){intsize=q.size();booleanflag=false;// process all oranges at current time levelfor(inti=0;i<size;i++){int[]cell=q.poll();intx=cell[0];inty=cell[1];// check all four directionsfor(int[]dir:directions){intnx=x+dir[0];intny=y+dir[1];// if cell is safe and has fresh orangeif(isSafe(nx,ny,n,m)&&mat[nx][ny]==1){// rot the orangemat[nx][ny]=2;q.add(newint[]{nx,ny});flag=true;}}}// if at least one orange got rotten, increase the timeif(flag)elapsedTime++;}// check if any fresh orange still remainsfor(inti=0;i<n;i++){for(intj=0;j<m;j++){if(mat[i][j]==1)return-1;}}returnelapsedTime;}//Driver Code Startspublicstaticvoidmain(String[]args){int[][]mat={{2,1,0,2,1},{1,0,1,2,1},{1,0,0,2,1}};System.out.println(orangesRot(mat));}}//Driver Code Ends
Python
#Driver Code Startsfromcollectionsimportdeque#Driver Code EndsdefisSafe(i,j,n,m):return0<=i<nand0<=j<m# function to perform bfs and find minimum timedeforangesRot(mat):n=len(mat)m=len(mat[0])# queue to store coordinates of rotten orangesq=deque()# counter of elapsed timeelapsedTime=0# push all initially rotten oranges into queueforiinrange(n):forjinrange(m):ifmat[i][j]==2:q.append((i,j))# directions for all four adjacent cellsdirections=[(1,0),(0,1),(-1,0),(0,-1)]# perform BFSwhileq:size=len(q)flag=False# process all oranges at current time levelfor_inrange(size):x,y=q.popleft()# check all four directionsfordx,dyindirections:nx,ny=x+dx,y+dy# if cell is safe and has fresh orangeifisSafe(nx,ny,n,m)andmat[nx][ny]==1:# rot the orangemat[nx][ny]=2q.append((nx,ny))flag=True# if at least one orange got rotten, increase the timeifflag:elapsedTime+=1# check if any fresh orange still remainsforiinrange(n):forjinrange(m):ifmat[i][j]==1:return-1returnelapsedTime#Driver Code Startsif__name__=="__main__":mat=[[2,1,0,2,1],[1,0,1,2,1],[1,0,0,2,1]]print(orangesRot(mat))#Driver Code Ends
C#
//Driver Code StartsusingSystem;usingSystem.Collections.Generic;classGFG{//Driver Code EndsstaticboolisSafe(inti,intj,intn,intm){return(i>=0&&i<n&&j>=0&&j<m);}// function to perform bfs and find minimum timestaticintorangesRot(int[,]mat){intn=mat.GetLength(0);intm=mat.GetLength(1);// queue to store coordinates of rotten orangesQueue<(int,int)>q=newQueue<(int,int)>();// counter of elapsed timeintelapsedTime=0;// push all initially rotten oranges into queuefor(inti=0;i<n;i++){for(intj=0;j<m;j++){if(mat[i,j]==2)q.Enqueue((i,j));}}// directions for all four adjacent cellsint[,]directions={{1,0},{0,1},{-1,0},{0,-1}};// perform BFSwhile(q.Count>0){intsize=q.Count;boolflag=false;// process all oranges at current time levelfor(ints=0;s<size;s++){var(x,y)=q.Dequeue();// check all four directionsfor(intk=0;k<4;k++){intnx=x+directions[k,0];intny=y+directions[k,1];// if cell is safe and has fresh orangeif(isSafe(nx,ny,n,m)&&mat[nx,ny]==1){// rot the orangemat[nx,ny]=2;q.Enqueue((nx,ny));flag=true;}}}// if at least one orange got rotten, increase the timeif(flag)elapsedTime++;}// check if any fresh orange still remainsfor(inti=0;i<n;i++){for(intj=0;j<m;j++){if(mat[i,j]==1)return-1;}}returnelapsedTime;}//Driver Code StartsstaticvoidMain(){int[,]mat={{2,1,0,2,1},{1,0,1,2,1},{1,0,0,2,1}};Console.WriteLine(orangesRot(mat));}}//Driver Code Ends
JavaScript
functionisSafe(i,j,n,m){returni>=0&&i<n&&j>=0&&j<m;}// function to perform bfs and find minimum timefunctionorangesRot(mat){constn=mat.length;constm=mat[0].length;// queue to store coordinates of rotten orangesconstq=[];// counter of elapsed timeletelapsedTime=0;// push all initially rotten oranges into queuefor(leti=0;i<n;i++){for(letj=0;j<m;j++){if(mat[i][j]===2){q.push([i,j]);}}}// directions for all four adjacent cellsconstdirections=[[1,0],[0,1],[-1,0],[0,-1]];// perform BFSwhile(q.length>0){letsize=q.length;letflag=false;// process all oranges at current time levelfor(lets=0;s<size;s++){const[x,y]=q.shift();// check all four directionsfor(const[dx,dy]ofdirections){constnx=x+dx;constny=y+dy;// if cell is safe and has fresh orangeif(isSafe(nx,ny,n,m)&&mat[nx][ny]===1){// rot the orangemat[nx][ny]=2;q.push([nx,ny]);flag=true;}}}// if at least one orange got rotten, increase the timeif(flag)elapsedTime++;}// check if any fresh orange still remainsfor(leti=0;i<n;i++){for(letj=0;j<m;j++){if(mat[i][j]===1)return-1;}}returnelapsedTime;}//Driver Code//Driver Code Startsconstmat=[[2,1,0,2,1],[1,0,1,2,1],[1,0,0,2,1]];console.log(orangesRot(mat));//Driver Code Ends