-
Notifications
You must be signed in to change notification settings - Fork 64
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Added Rotting Oranges Problem Solution
- Loading branch information
1 parent
0a8c17c
commit 9b0a65e
Showing
1 changed file
with
59 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | ||
} | ||
}; |