Skip to content

Commit 4f6fb61

Browse files
authored
Create 994. Rotting Oranges
1 parent c35d01b commit 4f6fb61

File tree

1 file changed

+66
-0
lines changed

1 file changed

+66
-0
lines changed

Graph/994. Rotting Oranges

Lines changed: 66 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,66 @@
1+
class Solution {
2+
public:
3+
int orangesRotting(vector<vector<int>>& grid) {
4+
// figure out the grid size
5+
int n = grid.size();
6+
int m = grid[0].size();
7+
//store {{row,col} , time}
8+
queue<pair<pair<int,int> , int>> q ;
9+
int visited[n][m];
10+
int cntFresh = 0;
11+
for(int i = 0 ; i < n ; i++){
12+
for(int j = 0 ; j < m ; j++){
13+
// if cell contains rotten orange
14+
if(grid[i][j] == 2){
15+
q.push({{i , j} , 0});
16+
// mark as visited (rotten) in visited array
17+
visited[i][j] = 2 ;
18+
}else{
19+
// if not rotten
20+
visited[i][j] = 0;
21+
}
22+
if(grid[i][j] == 1) cntFresh++ ;
23+
}
24+
}
25+
26+
int tm = 0 ;
27+
// delta row and delta column
28+
int delRow[] = {-1 , 0 , 1 , 0};
29+
int delCol[] = {0 , 1 , 0 , -1};
30+
int cnt = 0;
31+
while(!q.empty())
32+
{
33+
int row = q.front().first.first;
34+
int col = q.front().first.second;
35+
int t = q.front().second;
36+
tm = max(tm , t);
37+
q.pop();
38+
39+
40+
//exactly 4 neighbours
41+
for(int i = 0 ; i < 4 ; i++)
42+
{
43+
//look for neighbouring row and column
44+
int nRow = row + delRow[i];
45+
int nCol = col + delCol[i];
46+
// check for valid cell and
47+
//and for unvisited orange
48+
if(nRow < n && nRow >=0 && nCol<m && nCol >=0
49+
&& grid[nRow][nCol] == 1 && visited[nRow][nCol] != 2 )
50+
{
51+
// push in queue with timer increased
52+
q.push({{nRow , nCol} , t + 1 });
53+
// mark as rotten
54+
visited[nRow][nCol] = 2 ;
55+
cnt++ ;
56+
}
57+
}
58+
59+
}
60+
61+
// if all oranges are not rotten
62+
if(cnt != cntFresh) return -1 ;
63+
64+
return tm ;
65+
}
66+
};

0 commit comments

Comments
 (0)