你現在手裏有一份大小爲 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
輸入:[[1,0,1],[0,0,0],[1,0,1]]
輸出:2
解釋:
海洋區域 (1, 1) 和所有陸地區域之間的距離都達到最大,最大距離爲 2。
class Solution {
public int maxDistance(int[][] grid) {
int N = grid.length;
Queue<int[]> queue = new ArrayDeque<>();
// 將所有的陸地格子加入隊列
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
if (grid[i][j] == 1) {
queue.add(new int[]{i, j});
}
}
}
// 如果我們的地圖上只有陸地或者海洋,請返回 -1。
if (queue.isEmpty() || queue.size() == N * N) {
return -1;
}
int distance = -1;
while (!queue.isEmpty()) {
distance++;
int n = queue.size();
// 這裏一口氣取出 n 個結點,以實現層序遍歷
for (int i = 0; i < n; i++) {
int[] cell = queue.poll(); //poll()移除並返問隊列頭部的元素
int r = cell[0];
int c = cell[1];
// 遍歷上方單元格
if (r-1 >= 0 && grid[r-1][c] == 0) { //cell點正上方存在0
grid[r-1][c] = 2;
queue.add(new int[]{r-1, c});
}
// 遍歷下方單元格
if (r+1 < N && grid[r+1][c] == 0) { //cell點正下方存在0
grid[r+1][c] = 2;
queue.add(new int[]{r+1, c});
}
// 遍歷左邊單元格
if (c-1 >= 0 && grid[r][c-1] == 0) { //cell點正左邊存在0
grid[r][c-1] = 2;
queue.add(new int[]{r, c-1});
}
// 遍歷右邊單元格
if (c+1 < N && grid[r][c+1] == 0) { //cell點正右邊存在0
grid[r][c+1] = 2;
queue.add(new int[]{r, c+1});
}
}
}
return distance;
}
思路:首先把所有的陸地放在一個隊列中,然後執行第一次循環,將與原陸地距離爲1的海洋寫入改隊列中,然後把原陸地全部刪除;然後執行第二次循環,將於原陸地距離爲2的海洋寫入該隊列中,然後刪除與原陸地距離爲1的所有海洋;以此類推,當隊列中沒有海洋的時候,就結束循環。所以最遠距離就是當隊列中沒有值時的距離-1,所以爲了方便我們把起始距離設爲-1,則最後返回的就是最遠的距離。