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. 1 <= grid.length == grid[0].length <= 100
  2. grid[i][j] 不是 0 就是 1

Solution:

其实这一题跟number of islands很像,都是bfs把0变1的4-way搜索。对于每一个0(water),都存在离它最近的陆地距离,需要找到所有的距离中的最大值。解法就是把陆地放到deque队列中,再逐层搜索,每一次把d=1,d=2,...递增的所有的0都找到并变为1,逐层distance增加,最后返回的就是最大距离。

from collections import deque

class Solution(object):
    def maxDistance(self, grid):
        """
        :type grid: List[List[int]]
        :rtype: int
        """
        
        lands = deque([]) # python的队列是deque
        n, res = len(grid), -1
        for x in range(n):
            for y in range(n):
                if grid[x][y]: # land found
                    lands.append((x, y))
                    
        if len(lands) == 0 or len(lands) == n*n:
            return res
        
        dx, dy = [-1, 1, 0, 0], [0, 0, -1, 1]
        while lands:
            num = len(lands)
            for _ in range(num):
                x0, y0 = lands.popleft() # tuple还能这样用
                for i in range(4): # 4-way bfs search
                    x, y = x0 + dx[i], y0 + dy[i]
                    if 0 <= x < n  and 0 <= y < n  and not grid[x][y]: # water found
                        grid[x][y] = 1 # 很像number of islands
                        lands.append((x, y))
            res += 1
    
        return res       

  

猜你喜欢

转载自www.cnblogs.com/lowkeysingsing/p/11397991.html