leetcode1162.地圖分析
你現在手裏有一份大小爲 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。
示例 2:
輸入:[[1,0,0],[0,0,0],[0,0,0]]
輸出:4
解釋:
海洋區域 (2, 2) 和所有陸地區域之間的距離都達到最大,最大距離爲 4。
提示:
1 <= grid.length == grid[0].length <= 100
grid[i][j] 不是 0 就是 1
暴力解法(超時)
- 將所有的陸地和海洋取出,枚舉選出最遠的;
class Solution {
public int maxDistance(int[][] grid) {
List<Point> list1 = new ArrayList<>();
List<Point> list2 = new ArrayList<>();
for(int i = 0; i < grid.length; i++){
for(int j = 0; j < grid[i].length; j++){
if(grid[i][j] == 0)list1.add(new Point(i,j));
else list2.add(new Point(i,j));
}
}
if(list1.size() == 0 || list2.size() == 0)return -1;
int ans = 0;
for(Point p : list1){
int temp = 300;
for(Point p1 : list2){
temp = Math.min(Math.abs(p.x-p1.x) + Math.abs(p.y-p1.y),temp);
}
ans = Math.max(temp,ans);
}
return ans;
}
}
class Point{
int x;
int y;
Point(int x,int y){
this.x = x;
this.y = y;
}
}
正解:典型的bfs,多個源點一起出發,找到最遠的海洋即可;
class Solution {
public int maxDistance(int[][] grid) {
Queue<int[]> queue = new ArrayDeque<>();
for(int i = 0; i < grid.length; i++){
for(int j = 0; j < grid[i].length; j++){
if(grid[i][j] == 1)queue.offer(new int[] {i,j}); // 多個源點
}
}
int[] dx = {0,1,0,-1};
int[] dy = {-1,0,1,0};
int[] point = null;
boolean hasOcean = false;
while(!queue.isEmpty()){
point = queue.poll();
int x = point[0],y = point[1];
for(int i = 0; i < 4; i++){
int newX = x + dx[i];
int newY = y + dy[i];
if(newX >= 0 && newX < grid.length && newY >= 0 && newY < grid[0].length && grid[newX][newY] == 0){
hasOcean = true; // 是否有海洋
grid[newX][newY] = grid[x][y] + 1; // 直接更改原數組, 就不用額外的標記數組啦,並且把距離存儲進來
queue.offer(new int[] {newX,newY});
}
}
}
if(point == null || !hasOcean)return -1;
return grid[point[0]][point[1]] - 1;
}
}