1.你现在手里有一份大小为 N x N 的『地图』(网格) grid,上面的每个『区域』(单元格)都用 0 和 1 标记好了。其中 0 代表海洋,1 代表陆地,你知道距离陆地区域最远的海洋区域是是哪一个吗?请返回该海洋区域到离它最近的陆地区域的距离。
我们这里说的距离是『曼哈顿距离』( Manhattan Distance):(x0, y0) 和 (x1, y1) 这两个区域之间的距离是 |x0 - x1| + |y0 - y1| 。
如果我们的地图上只有陆地或者海洋,请返回 -1。
示例 1:
输入:[[1,0,1],[0,0,0],[1,0,1]]
输出:2
解释:
海洋区域 (1, 1) 和所有陆地区域之间的距离都达到最大,最大距离为 2。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/as-far-from-land-as-possible
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
方法一:BFS
求出每一个海洋区域(grid[i][j] == 0 的区域)的「最近陆地区域」,然后记录下它们的距离,然后在这些距离里面取一个最大值。
class Solution { public: static constexpr int dx[4] = {-1, 0, 1, 0}, dy[4] = {0, 1, 0, -1};//上下左右增量坐标 static constexpr int MAX_N = 100 + 5;//记录走过的位置 struct Coordinate { int x, y, step; }; int n, m; vector<vector<int>> a; bool vis[MAX_N][MAX_N]; int findNearestLand(int x, int y) { memset(vis, 0, sizeof vis); queue <Coordinate> q; q.push({x, y, 0}); vis[x][y] = 1;//此点走过 while (!q.empty()) { auto f = q.front(); q.pop(); for (int i = 0; i < 4; ++i) { int nx = f.x + dx[i], ny = f.y + dy[i];//上下左右寻找 if (!(nx >= 0 && nx <= n - 1 && ny >= 0 && ny <= m - 1)) continue; if (!vis[nx][ny]) { q.push({nx, ny, f.step + 1}); vis[nx][ny] = 1; if (a[nx][ny]) return f.step + 1;//是陆地,就+1返回 } } } return -1; } int maxDistance(vector<vector<int>>& grid) { this->n = grid.size(); this->m = grid.at(0).size(); a = grid; int ans = -1; for (int i = 0; i < n; ++i) { for (int j = 0; j < m; ++j) { if (!a[i][j]) { ans = max(ans, findNearestLand(i, j)); } } } return ans; } };