1162. As Far from Land as Possible
Last updated
Last updated
Input: [[1,0,1],[0,0,0],[1,0,1]]
Output: 2
Explanation:
The cell (1, 1) is as far as possible from all the land with distance 2.Input: [[1,0,0],[0,0,0],[0,0,0]]
Output: 4
Explanation:
The cell (2, 2) is as far as possible from all the land with distance 4.// BFS
int maxDistance(vector<vector<int>>& grid) { // time: O(n^2); space: O(n^2)
const int n = grid.size();
const vector<pair<int, int> > dirs({{-1, 0}, {1, 0}, {0, -1}, {0, 1}});
queue<pair<int, int> > q;
for (int i = 0; i < n; ++i) {
for (int j = 0; j < n; ++j) {
if (grid[i][j] == 1) {
q.push({i, j});
}
}
}
int level = 0;
while (!q.empty()) {
++level;
for (int k = q.size() - 1; k >= 0; --k) {
int r = q.front().first, c = q.front().second;
q.pop();
for (const pair<int, int>& dir : dirs) {
int new_r = r + dir.first, new_c = c + dir.second;
if (new_r < 0 || new_r >= n || new_c < 0 || new_c >= n || grid[new_r][new_c] != 0) continue;
grid[new_r][new_c] = level + 1;
q.push({new_r, new_c});
}
}
}
return level == 1 ? -1 : (level - 1);
}