File tree 1 file changed +36
-0
lines changed
August-LeetCoding-Challenge/09-Rotting-Oranges
1 file changed +36
-0
lines changed Original file line number Diff line number Diff line change
1
+
2
+ const int dx[4 ] = { -1 , 0 , 1 , 0 };
3
+ const int dy[4 ] = { 0 , -1 , 0 , 1 };
4
+ typedef pair<int ,int > ip;
5
+ class Solution {
6
+ public:
7
+ int orangesRotting (vector<vector<int >>& grid) {
8
+ const int m=grid.size (), n=grid[0 ].size ();
9
+ unordered_set<int > freshes;
10
+ queue<ip> rottens;
11
+ int r=0 ;
12
+ for (int i=0 ; i<m; ++i){
13
+ for (int j=0 ; j<n; ++j){
14
+ if (grid[i][j]){
15
+ if (grid[i][j]==1 ) freshes.insert (n*i+j);
16
+ else rottens.emplace (i,j);
17
+ }
18
+ }
19
+ }
20
+ while (!rottens.empty ()){
21
+ for (int i=0 , qsz=rottens.size (); i<qsz; ++i){
22
+ ip f=rottens.front (); rottens.pop (); auto [x,y] = f;
23
+ for (int j=0 ; j<4 ; ++j){
24
+ int tox=dx[j]+x, toy=dy[j]+y, ind = n*tox+toy;
25
+ if (tox>=0 && toy>=0 && tox<m && toy<n && freshes.count (ind))
26
+ freshes.erase (ind), rottens.emplace (tox,toy);
27
+ }
28
+
29
+ }
30
+ if (!rottens.empty ())
31
+ ++r;
32
+ }
33
+ if (!freshes.empty ()) return -1 ;
34
+ else return r;
35
+ }
36
+ };
You can’t perform that action at this time.
0 commit comments