-
Notifications
You must be signed in to change notification settings - Fork 0
/
asfarfromlandaspossible.cpp
48 lines (48 loc) · 1.57 KB
/
asfarfromlandaspossible.cpp
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
class Solution {
public:
int maxDistance(vector<vector<int>>& grid) {
int i, j, n = grid.size();
int x, y;
int ans = -1;
pair<int,pair<int,int> > pred;
queue<pair<int,pair<int,int> > > Q;
if (n > 1) {
queue<pair<int,pair<int,int> > > Q;
for (i = 0; i < n; i++) {
for (j = 0; j < n; j++) {
if (grid[i][j] == 1) {
grid[i][j] = 2;
Q.push({0,{i,j}});
}
}
}
while (!Q.empty()) {
pred = Q.front();
Q.pop();
x = pred.second.first;
y = pred.second.second;
if (x+1 < n && !grid[x+1][y]) {
Q.push({pred.first+1,{x+1,y}});
grid[x+1][y] = 2;
ans = max(ans,pred.first+1);
}
if (x-1 > -1 && !grid[x-1][y]) {
Q.push({pred.first+1,{x-1,y}});
grid[x-1][y] = 2;
ans = max(ans,pred.first+1);
}
if (y+1 < n && !grid[x][y+1]) {
Q.push({pred.first+1,{x,y+1}});
grid[x][y+1] = 2;
ans = max(ans,pred.first+1);
}
if (y-1 > -1 && !grid[x][y-1]) {
Q.push({pred.first+1,{x,y-1}});
grid[x][y-1] = 2;
ans = max(ans,pred.first+1);
}
}
}
return ans;
}
};