-
Notifications
You must be signed in to change notification settings - Fork 14
Expand file tree
/
Copy path1162.maxDistance.cpp
More file actions
67 lines (54 loc) · 1.89 KB
/
1162.maxDistance.cpp
File metadata and controls
67 lines (54 loc) · 1.89 KB
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
class Solution {
public:
int maxDistance(vector<vector<int>>& grid) {
queue<pair<int, int>> lands;
int m = grid.size();
if (m == 0) return 0;
int n = grid[0].size();
if (n == 0) return 0;
int ans = 0;
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if (grid[i][j] == 1) {
lands.push(make_pair(i, j));
}
}
}
if (lands.size() == 0 || lands.size() == m*n) return -1;
int dx[4] = {1,-1,0,0};
int dy[4] = {0,0,1,-1};
while(!lands.empty()) {
int size = lands.size();
for (int c = 0; c < size; c++) {
pair<int, int> land = lands.front();
lands.pop();
int i = land.first;
int j = land.second;
if (grid[i][j] == 2) continue;
for (int d = 0; d < 4; d++) {
int ii = i + dx[d];
int jj = j + dy[d];
if (ii < 0 || ii >= m || jj < 0 || jj >= n) continue;
if (grid[ii][jj] == 2 || grid[ii][jj] < 0) continue;
cout << ii << " " << jj << endl;
if (grid[ii][jj] == 1) {
grid[i][j] = 2;
lands.push(make_pair(ii, jj));
continue;
}
if (grid[ii][jj] == 0) {
if (grid[i][j] >= 1) {
grid[ii][jj] = -1;
} else {
grid[ii][jj] = grid[i][j] - 1;
}
lands.push(make_pair(ii, jj));
}
ans = max(ans, -grid[ii][jj]);
}
grid[i][j] = 2;
}
}
return ans;
}
};