-
Notifications
You must be signed in to change notification settings - Fork 0
/
Rotten oranges
56 lines (50 loc) · 1.59 KB
/
Rotten oranges
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
int orangesRotting(vector<vector<int>>& grid) {
int m = grid.size() ;
int n = grid[0].size() ;
vector<vector<int>> visited ( m , vector <int>(n , 0) ) ;
queue <pair < pair <int , int > , int > > q;
for(int i = 0 ; i < grid.size() ; i++)
{
for(int j =0 ; j < grid[0].size() ; j++)
{
if(grid[i][j] == 2)
{
q.push( {{i , j} , 0}) ;
visited[i][j] = 1 ;
}
}
}
int maxmin = 0 ;
while( !q.empty())
{
int i = q.front().first.first ;
int j = q.front().first.second ;
int min = q.front().second ;
q.pop() ;
int a[4] = {1 , 0 , -1, 0} ;
int b[4] = {0 , 1, 0 , -1};
for(int k = 0 ; k < 4 ; k++)
{
int x = a[k] ;
int y = b[k] ;
// cout << i + x << j + y << endl ;
if(i + x < m && j + y < n && i + x >= 0 && j + y >= 0 && visited[i + x][j + y] == 0 && grid[i + x][j + y] == 1)
{
q.push({{i + x , j + y} , min + 1}) ;
maxmin = max(maxmin , min + 1) ;
visited[i + x][j + y] = 1;
}
}
}
for(int i = 0 ; i < m ; i++)
{
for(int j = 0 ; j < n ; j++)
{
if(visited[i][j] == 0 && grid[i][j] == 1)
{
return -1 ;
}
}
}
return maxmin ;
}