海洋陆地地图

from collections import deque
class Solution:
    def maxDistance(self, grid):
        queue = deque()
        row = len(grid)
        col = len(grid[0])
        res = [[0 for _ in range(row)]for _ in range(col)]
        visited = [[False for _ in range(row)]for _ in range(col)]
        dectection = [[1,0],[-1,0],[0,1],[0,-1]]
        for i in range(row):
            for j in range(col):
                if grid[i][j] == 1:
                    queue.append((i,j))
                    visited[i][j] = True
        if len(queue) == 0 or len(queue) == col*row:
            return -1
        while queue:
            i,j = queue.popleft()
            for index in dectection:
                new_x = index[0] + i
                new_y = index[1] + j
                if 0<= new_x < row and 0<= new_y <col and visited[new_x][new_y] != True:
                    res[new_x][new_y] = res[i][j] + 1
                    queue.append((new_x,new_y))
                    visited[new_x][new_y] = True
        print(res)
        max1 = 0
        for i in range(row):
            for j in range(col):
                max1 = max(res[i][j],max1)
        return max1

猜你喜欢

转载自blog.csdn.net/aaaqqq1234/article/details/108319626