题目描述:你现在手里有一份大小为 N x N 的『地图』(网格)
grid,上面的每个『区域』(单元格)都用0和1标记好了。其中0代表海洋,1代表陆地,你知道距离陆地区域最远的海洋区域是是哪一个吗?请返回该海洋区域到离它最近的陆地区域的距离。我们这里说的距离是『曼哈顿距离』( Manhattan Distance):
(x0, y0)和(x1, y1)这两个区域之间的距离是|x0 - x1| + |y0 - y1|。如果我们的地图上只有陆地或者海洋,请返回
-1。
eg:
示例 1:
输入:[[1,0,1],[0,0,0],[1,0,1]]
输出:2
解释:
海洋区域 (1, 1) 和所有陆地区域之间的距离都达到最大,最大距离为 2。
示例 2:
输入:[[1,0,0],[0,0,0],[0,0,0]]
输出:4
解释:
海洋区域 (2, 2) 和所有陆地区域之间的距离都达到最大,最大距离为 4。思路描述:考虑最朴素的方法,即求出每一个海洋区域(
grid[i][j] == 0的区域)的「最近陆地区域」,然后记录下它们的距离,然后在这些距离里面取一个最大值。BFS
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;
}
}
}
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;
}
};上面是单纯使用BFS,其实在方法一中我们已经发现我们 BFS 的过程是求最短路的过程,但是这里不是求某一个海洋区域到陆地区域的最短路,而是求所有的海洋区域到陆地区域这个「点集」的最短路。使用Dijkstra算法
class Solution {
public:
static constexpr int MAX_N = 100 + 5;
static constexpr int INF = int(1E6);
static constexpr int dx[4] = {-1, 0, 1, 0}, dy[4] = {0, 1, 0, -1};
int n;
int d[MAX_N][MAX_N];
struct Status {
int v, x, y;
bool operator < (const Status &rhs) const {
return v > rhs.v;
}
};
priority_queue <Status> q;
int maxDistance(vector<vector<int>>& grid) {
this->n = grid.size();
auto &a = grid;
for (int i = 0; i < n; ++i) {
for (int j = 0; j < n; ++j) {
d[i][j] = INF;
}
}
for (int i = 0; i < n; ++i) {
for (int j = 0; j < n; ++j) {
if (a[i][j]) {
d[i][j] = 0;
q.push({0, i, j});
}
}
}
while (!q.empty()) {
auto f = q.top(); 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 <= n - 1)) continue;
if (f.v + 1 < d[nx][ny]) {
d[nx][ny] = f.v + 1;
q.push({d[nx][ny], nx, ny});
}
}
}
int ans = -1;
for (int i = 0; i < n; ++i) {
for (int j = 0; j < n; ++j) {
if (!a[i][j]) ans = max(ans, d[i][j]);
}
}
return (ans == INF) ? -1 : ans;
}
};