从陆地出发,进行多源BFS,最后一个到达的海洋就满足要求,注意由于是多源BFS,有一个超级原点,所以步长要-1
const int dx[] = {0, 1, -1, 0};
const int dy[] = {1, 0, 0, -1};
class Solution {
public:
int maxDistance(vector<vector<int>>& grid) {
int n = grid.size(), m = grid[0].size();
queue<pair<int, int>> q;
bool sea = false;
for (int i = 0; i < grid.size(); i++) {
for (int j = 0; j < grid[0].size(); j++) {
if (grid[i][j] == 1) {
q.push({i, j});
}
if (grid[i][j] == 0) {
sea = true;
}
}
}
int res = -1;
if (!sea) return res;
while (!q.empty()) {
int t = q.size();
while (t--) {
auto [x, y] = q.front(); q.pop();
for (int i = 0; i < 4; i++) {
int a = x + dx[i];
int b = y + dy[i];
if (a >= 0 && a < n && b >= 0 && b < m && grid[a][b] != 1) {
grid[a][b] = 1;
q.push({a, b});
}
}
}
res++;
}
return res;
}
};