Skip to content

Commit f476264

Browse files
authored
Create 994.cpp
1 parent 96f80a0 commit f476264

File tree

1 file changed

+50
-0
lines changed

1 file changed

+50
-0
lines changed

994/994.cpp

+50
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
class Solution {
2+
public:
3+
int dx[4] = {0, 0, 1, -1};
4+
int dy[4] = {1, -1, 0, 0};
5+
bool valid(int r, int c, int n, int m) {return (r >= 0 and r < n and c >= 0 and c < m);}
6+
7+
int orangesRotting(vector<vector<int>>& grid) {
8+
queue<pair<int,int>> q;
9+
int n = grid.size();
10+
int m = grid[0].size();
11+
12+
int fresh = 0;
13+
for(int i = 0; i < n; i++){
14+
for(int j = 0; j < m; j++){
15+
if(grid[i][j] == 2){
16+
q.push({i,j});// rotten will start spreading
17+
}else if(grid[i][j] == 1)
18+
fresh++;
19+
}
20+
}
21+
22+
if(fresh == 0)
23+
return 0;
24+
25+
int time = -1;
26+
while(!q.empty()){
27+
int sz = q.size();
28+
time++;
29+
30+
while(sz--){
31+
auto [x,y] = q.front();
32+
q.pop();
33+
34+
for(int i = 0; i < 4; i++){
35+
int r = x + dx[i];
36+
int c = y + dy[i];
37+
38+
if(valid(r,c,n,m) and grid[r][c] == 1){
39+
// only go to a fresh apple
40+
q.push({r,c});
41+
grid[r][c] = 2;
42+
fresh--;
43+
}
44+
}
45+
}
46+
}
47+
48+
return fresh == 0 ? time: -1;
49+
}
50+
};

0 commit comments

Comments
 (0)