leetCode-1162. 地图分析

题目:

你现在手里有一份大小为 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

解题思路:

广度优先搜索的思路,可以借助队列来实现:
1、把所有的陆地入队
2、从各个陆地一层一层的向海洋不断扩大,直到覆盖整个地图
那么,最后到达了某个未访问过的海洋就是距离陆地区域最远的海洋区域

代码实现:

class Solution {
    public int maxDistance(int[][] grid) {
         // 四个方向
        int[][] directions = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}}; 
          		  		
        int rows = grid.length;
		int cols = grid[0].length;

       Queue<int[]> queue = new ArrayDeque<>();
        for (int i = 0; i < rows; i++) {
            for (int j = 0; j < cols; j++) {
                //1、把所有的陆地入队
                if (grid[i][j] == 1) {
                    queue.offer(new int[] {i, j});
                }
            }
        }

        int size = queue.size();
        //只存在海洋或者只存在陆地,返回-1
        if (size == 0 || size == rows * cols) {
            return -1;
        }
        
        int distance = 0;     
        while (!queue.isEmpty()) {
            int currentQueueSize = queue.size();
              //2、从各个陆地一层一层的向海洋不断扩大,直到覆盖整个地图
            for (int i = 0; i < currentQueueSize; i++) {
                int[] current = queue.poll();
                int tx = current[0];
                int ty = current[1];
                for (int[] direction : directions) {
                    int m = tx + direction[0];
                    int n = ty + direction[1];
                    if (isInGrid(m, n, rows,cols) && grid[m][n] == 0) {
                        grid[m][n] = 1;
                        queue.offer(new int[] {m, n});
                    }
                }
            }
            distance++;
        }
        // 最后一步,没有扩大,因此需要减 1
        return distance - 1;
    }
  
     //是否在网格区域范围内 
    private boolean isInGrid (int x, int y, int rows,int cols) {
        return 0 <= x && x < rows && 0 <= y && y < cols;
    }    
}

复杂度分析:

  • 时间复杂度:O(N^2),这里 N 是网格的边长。二维表格里所有的元素都会被搜索一遍;
  • 空间复杂度:O(N^2),最坏情况下,方格里全部是陆地(1)的时候,元素全部会进队列。
发布了157 篇原创文章 · 获赞 1 · 访问量 2675

猜你喜欢

转载自blog.csdn.net/qq_34449717/article/details/105188698