序号:1162
难度:中等
题目:地图分析
开发语言:python或C++
链接:https://leetcode-cn.com/problems/as-far-from-land-as-possible
1、bfs框架
while queue 非空:
node = queue.pop()
for node 的所有相邻节点m:
If m没有被访问过:
queue.push(m)
2、题解:
class Solution {
public:
int dx[4] = {1,-1,0,0};
int dy[4] = {0,0,1,-1};
int maxDistance(vector<vector<int>>& grid) {
queue<pair<int, int>> q;
int m = grid.size();
int n = grid[0].size();
for(int i= 0;i<m;i++)
for (int j = 0; j < n; j++)
{
if (grid[i][j] == 1)
{
q.push(make_pair(i,j));
}
}
int count = -1;
while (!q.empty())
{
int num = q.size();
if (num == m * n)
return -1;
count++;
for (int j = 0; j < num; j++)
{
pair<int, int> pa = q.front();
q.pop();
for (int i = 0; i < 4; i++)
{
int new_x = pa.first + dx[i];
int new_y = pa.second + dy[i];
if (new_x >= 0 and new_x < m and new_y >= 0 and new_y < n)
{
if (grid[new_x][new_y] == 0)
{
grid[new_x][new_y] = 2;
q.push(make_pair(new_x, new_y));
}
}
}
}
}
return count;
}
};