File tree Expand file tree Collapse file tree 1 file changed +61
-0
lines changed Expand file tree Collapse file tree 1 file changed +61
-0
lines changed Original file line number Diff line number Diff line change
1
+ class Solution {
2
+ public:
3
+
4
+ int orangesRotting (vector<vector<int >>& grid) {
5
+ int i,j;
6
+ int cnt1=0 ;
7
+ queue<pair<int ,int > > q;
8
+
9
+ // The concept of the problem lies in the fact:
10
+ // Start a bfs with all the rotten oranges in the queue
11
+ // Traverse in all possible diretions in the grid, and keep track of the levels which also acts as the time to for all the oranges to rott.
12
+
13
+ for (i=0 ;i<grid.size ();i++)
14
+ {
15
+ for (j=0 ;j<grid[i].size ();j++)
16
+ {
17
+ if (grid[i][j]==2 )
18
+ {
19
+ q.push ({i,j});
20
+ }
21
+ if (grid[i][j]==1 )
22
+ {
23
+ cnt1++;
24
+ }
25
+ }
26
+ }
27
+
28
+
29
+ int lev=0 ;
30
+ int dx[] = {1 ,0 ,-1 ,0 };
31
+ int dy[] = {0 ,1 ,0 ,-1 };
32
+ while (!q.empty ())
33
+ {
34
+ int s = q.size ();
35
+ int x;
36
+ for (x=0 ;x<s;x++)
37
+ {
38
+ auto p = q.front ();
39
+ q.pop ();
40
+ int y;
41
+ for (y=0 ;y<4 ;y++)
42
+ {
43
+ int n_x = p.first + dx[y];
44
+ int n_y = p.second + dy[y];
45
+ if (n_x>=0 && n_x<grid.size () && n_y>=0 && n_y<grid[0 ].size () && (grid[n_x][n_y]==1 ))
46
+ {
47
+ grid[n_x][n_y] = 2 ;
48
+ q.push ({n_x,n_y});
49
+ cnt1--;
50
+ }
51
+ }
52
+ }
53
+ lev++;
54
+ }
55
+ if (lev==0 && cnt1==0 )
56
+ return 0 ;
57
+ int ans = (cnt1==0 ) ? lev-1 : -1 ;
58
+ return ans;
59
+
60
+ }
61
+ };
You can’t perform that action at this time.
0 commit comments