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
57
58
59
60
61
62
63
64
65
66
67
68
69
|
#define x first
#define y second
typedef pair<int,int> PII ;
const int N = 20 ;
const int INF = 0x3f3f3f3f ;
int dist[N][N];
PII q[N*N];
int n,m;
bool st[20][20];
void init() {
memset(dist,INF,sizeof(dist));
n = 0 ;
m = 0 ;
}
int wx[] = {1,-1,0,0} ;
int wy[] = {0,0,1,-1};
void bfs(int sx,int sy,vector<vector<int>>& g) {
memset(st,0,sizeof(st));
int hh = 0 , tt = 0 ;
q[0] = {sx,sy};
dist[sx][sy] = 0 ;
st[sx][sy] = 1;
while(hh <= tt) {
PII t = q[hh ++ ];
for(int i = 0 ; i < 4 ; i ++ ) {
int dx = t.x + wx[i];
int dy = t.y + wy[i];
if(dx < 0 || dx >= n || dy < 0 || dy >= m ) continue;
if(g[dx][dy] == 0 || g[dx][dy] == 2) continue ;
if(st[dx][dy]) continue;
st[dx][dy] = 1;
dist[dx][dy] = min(dist[dx][dy], dist[t.x][t.y] + 1);
q[++tt] = {dx,dy};
}
}
}
class Solution {
public:
int orangesRotting(vector<vector<int>>& grid) {
init();
n = grid.size();
m = grid[0].size();
for(int i = 0 ; i < n ; i ++ )
for(int j = 0 ; j < m ; j ++ ) {
if(grid[i][j] == 2) {
bfs(i,j,grid);
}
}
int ans = 0;
for(int i = 0 ; i < n ; i ++ )
for(int j = 0 ; j < m ; j ++ ) {
if(grid[i][j] == 1 ) {
if (dist[i][j] == INF)return -1;
else ans = max(ans , dist[i][j]);
}
}
return ans ;
}
};
|