跳至主要內容

离开陆地的最远距离


离开陆地的最远距离

题目

有一个NxN的网格grid,上面的每个网格都用0和1标记好了。其中0代表海洋,1代表陆地。请在其中找出一个海洋单元格,这个海洋单元格到离它最近的陆地单元格的距离是最大的。 距离是指曼哈顿距离,即(x0, y0)和(x1, y1)这两个单元格之间的距离是|x0-x1|+|y0-y1|。

示例1:

输入:[[1,0,1],[0,0,0],[1,0,1]]
输出:2
解释:海洋单元格(1,1)和所有陆地单元格之间的距离都达到最大,最大距离为2。

解答

public 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[][] moves = {
            {-1, 0}, {1, 0}, {0, -1}, {0, 1},
        };

        int distance = -1; // 记录当前遍历的层数(距离)
        while (!queue.isEmpty()) {
            distance++;
            int n = queue.size();
            for (int i = 0; i < n; i++) { 
                int[] node = queue.poll();
                int r = node[0];
                int c = node[1];
                for (int[] move : moves) {
                    int r2 = r + move[0];
                    int c2 = c + move[1];
                    if (inArea(grid, r2, c2) && grid[r2][c2] == 0) {
                        // 将已经遍历过的格子标记为2
                        grid[r2][c2] = 2;
                        queue.add(new int[]{r2, c2});
                    }
                }
            }
        }

        return distance;
    }

    // 判断坐标 (r, c) 是否在网格中
    boolean inArea(int[][] grid, int r, int c) {
        return 0 <= r && r < grid.length 
            && 0 <= c && c < grid[0].length;
    }
}
上次编辑于:
贡献者: Neil