接下来进行第4轮扩张,发现周围已经没有0了(即已经找不到可以入队列的点了),所以队列为空,结束程序,4-1就是答案!
class Solution {
public:
int maxDistance(vector<vector<int>>& grid) {
queue<pair<int, int>>myqueue;
for (int i = 0; i < grid.size(); i++)
{
for (int j = 0; j < grid[0].size(); j++)
{
if (grid[i][j] == 0)continue;
myqueue.push({ i,j });
}
}
if (myqueue.empty() || myqueue.size() == grid.size()*grid[0].size())return -1;//特判,grid全0或全1的情况
int dx[] = { 0,0,-1,1 };
int dy[] = { 1,-1,0,0 };
int ans = 1;//ans表示当前是第几轮扩张
//start
while (!myqueue.empty())
{
pair<int, int> temp = myqueue.front();//auto temp=myqueue.front();
myqueue.pop();
ans = grid[temp.first][temp.second];
for (int i = 0; i < 4; i++)
{
int x_new = temp.first + dx[i];
int y_new = temp.second + dy[i];
if (x_new < 0 || x_new >= grid[0].size())continue;
if (y_new < 0 || y_new >= grid.size())continue;
if (grid[x_new][y_new] != 0)continue;
grid[x_new][y_new] = ans + 1;//在原有"陆地"基础上+1
myqueue.push({ x_new,y_new });
}
}
return ans - 1;
}
};