Skip to content

Commit

Permalink
Added Rotting Oranges Problem Solution
Browse files Browse the repository at this point in the history
  • Loading branch information
jyoti-bhasin committed Oct 30, 2022
1 parent 0a8c17c commit 9b0a65e
Showing 1 changed file with 59 additions and 0 deletions.
59 changes: 59 additions & 0 deletions leetcode/Rotting_Oranges.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
class Solution {
public:
int orangesRotting(vector<vector<int>>& grid) {

int n=grid.size();
int m=grid[0].size();

int vis[n][m];
queue < pair< pair< int,int >,int > > q;
int fresh=0;
for(int i=0;i<n;i++)
{
for(int j=0;j<m;j++)
{
if(grid[i][j]==2)
{
q.push({{i,j},0});
vis[i][j]=2;
}
else{
vis[i][j]=0;
}
if(grid[i][j]==1)
fresh++;
}
}

int tm=0;

int cnt=0;
while(!q.empty())
{
int delrow[]={1,0,-1,0};
int delcol[]={0,-1,0,1};
int r=q.front().first.first;
int c=q.front().first.second;
int t=q.front().second;
tm=max(tm,t);
q.pop();

for(int i=0;i<4;i++)
{
int nrow=r+delrow[i];
int ncol=c+delcol[i];
if(nrow>=0 && nrow<n && ncol>=0 && ncol<m && grid[nrow][ncol]==1 && vis[nrow][ncol]!=2)
{
q.push({{nrow,ncol},t+1});
vis[nrow][ncol]=2;
cnt++;

}
}
}

if(cnt != fresh) return -1;

return tm;
}
};

0 comments on commit 9b0a65e

Please sign in to comment.