Problem
Given an N x N grid containing only values 0 and 1, where 0 represents water and 1 represents land, find a water cell such that its distance to the nearest land cell is maximized and return the distance.
The distance used in this problem is the Manhattan distance: the distance between two cells (x0, y0) and (x1, y1) is |x0 - x1| + |y0 - y1|.
If no land or water exists in the grid, return -1.
Example1
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.
Example2
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.
Solution
多源BFS。
class Solution {
public:
int maxDistance(vector<vector<int>>& grid) {
if(grid.empty())
return -1;
int rows = grid.size();
int cols = grid[0].size();
queue<pair<int,int>> q;
for(int r = 0;r < rows;++r)
for(int c = 0;c < cols;++c)
{
if(grid[r][c] == 1)
{
q.push(pair<int,int>(r,c));
}
}
if(q.empty() || q.size() == rows * cols)
{
return -1;
}
vector<pair<int,int>> dir = {{-1,0},{1,0},{0,-1},{0,1}};
int ret = -1;
while(!q.empty())
{
++ret;
int q_size = q.size();
for(int i = 0;i<q_size;++i)
{
pair<int,int> cur = q.front();
q.pop();
for(int j = 0;j<dir.size();++j)
{
int r = cur.first + dir[j].first;
int c = cur.second + dir[j].second;
if(r >= 0 && r < rows && c >=0 && c< cols && grid[r][c] == 0)
{
q.push(pair<int,int>(r,c));
grid[r][c] = 2;
}
}
}
}
return ret;
}
};