一、题目:
提示:
1 <= grid.length == grid[0].length <= 100
grid[i][j] 不是 0 就是 1
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/as-far-from-land-as-possible
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
二、题解:BFS
Tree的BFS:root节点先入队,然后再一层一层的遍历
图的BFS也是一样
区别如下:
1、tree只有1个root,而图可以有多个源点,所以首先需要把多个源点都入队。
2、tree是有向的因此不需要标志是否访问过,而对于无向图来说,必须得标志是否访问过!
并且为了防止某个节点多次入队,需要在入队之前就将其设置成已访问!
参考:
作者:sweetiee
链接:https ://leetcode-cn.com/problems/as-far-from-land-as-possible/solution/jian-dan-java-miao-dong-tu-de-bfs-by-sweetiee/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
三、代码:
//Tree的BFS:root节点先入队,然后再一层一层的遍历
//图的BFS也是一样
//区别如下:
//1、tree只有1个root,而图可以有多个源点,所以首先需要把多个源点都入队。
//2、tree是有向的因此不需要标志是否访问过,而对于无向图来说,必须得标志是否访问过!
// 并且为了防止某个节点多次入队,需要在入队之前就将其设置成已访问!
//参考:
//作者:sweetiee
//链接:https ://leetcode-cn.com/problems/as-far-from-land-as-possible/solution/jian-dan-java-miao-dong-tu-de-bfs-by-sweetiee/
//来源:力扣(LeetCode)
//著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
// BFS
class Solution {
public:
int maxDistance(vector<vector<int>>& grid) {
if (grid.empty()) {
return -1;
}
int row = grid.size();
int col = grid[0].size();
queue<pair<int, int>> landQue;
for (size_t i = 0; i < row; i++) {
for (size_t j = 0; j < col; j++) {
if (grid[i][j] != 0) {
landQue.push(pair<int, int>(i, j));
}
}
}
// 全是陆地or海洋
if (landQue.empty() || landQue.size() == row * col) {
return -1;
}
int dx[] = { 1, 0, -1, 0 };
int dy[] = { 0, 1, 0, -1 };
int maxLen = -1;
while (!landQue.empty()) {
pair<int, int> tmp = landQue.front();
landQue.pop();
for (size_t i = 0; i < 4; i++) {
int tmpX = tmp.first + dx[i];
int tmpY = tmp.second + dy[i];
if (tmpX < 0 || tmpX >= row || tmpY < 0 || tmpY >= col || grid[tmpX][tmpY] != 0) {
continue;
}
landQue.push(pair<int, int>(tmpX, tmpY));
grid[tmpX][tmpY] = grid[tmp.first][tmp.second] + 1;
maxLen = max(maxLen, grid[tmpX][tmpY]);
}
}
// 减去海洋起始的1
return maxLen - 1;
}
};