1162. 地图分析

你现在手里有一份大小为 n x n 的 网格 grid,上面的每个 单元格 都用 0 和 1 标记好了。其中 0 代表海洋,1 代表陆地。

请你找出一个海洋单元格,这个海洋单元格到离它最近的陆地单元格的距离是最大的,并返回该距离。如果网格上只有陆地或者海洋,请返回 -1。

我们这里说的距离是「曼哈顿距离」( Manhattan Distance):(x0, y0) 和 (x1, y1) 这两个单元格之间的距离是 |x0 - x1| + |y0 - y1| 。

来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/as-far-from-land-as-possible
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。


思路:找海洋陆地的距离,利用涟漪的思想,将陆地一点一点的向外扩张,最后扩张到的就是最大距离。


class Solution {
    public int maxDistance(int[][] grid) {

        Queue<int[]> queue = new LinkedList<>();
        int count = 0;

        for(int i=0;i<grid.length;i++) {
            for(int j=0;j<grid[0].length;j++) {
                if(grid[i][j] == 1) {
                    queue.add(new int[]{i,j});
                }
            }
        }
        if(queue.isEmpty() || queue.size() == grid.length*grid[0].length) {
            return -1;
        }

        while(!queue.isEmpty()) {
            int size = queue.size();
            for(int t=0;t<size;t++) {
                int[] pos = queue.poll();
                int[] dx = {0,0,1,-1};
                int[] dy = {1,-1,0,0};

                for(int i=0;i<4;i++) {
                    int newX = pos[0] + dx[i];
                    int newY = pos[1] + dy[i];
                    if(newX <0 || newX>=grid.length || newY < 0 || newY >= grid[0].length || grid[newX][newY] == 1) {
                        continue;
                    }
                    grid[newX][newY] = 1;
                    queue.add(new int[]{newX,newY});
                   
                }
                
            }
            count++;
        }

        return count-1;

    }
}
posted @ 2022-05-24 12:12  一颗青菜  阅读(14)  评论(0)    收藏  举报