Участник:Polina Potapova/as-far-from-land-as-possible

Материал из DISCOPAL
Перейти к: навигация, поиск

https://leetcode.com/problems/as-far-from-land-as-possible

class Solution(object):
    def maxDistance(self, grid):
        """
        :type grid: List[List[int]]
        :rtype: int
        """
        lenght = len(grid)
        plan = [(i, j, 0) for j in range(lenght) for i in range(lenght) if grid[i][j] == 1]        
        d = [(0, 1), (0, -1), (1, 0), (-1, 0)]
        result = 0
        while plan:
            i, j, result = plan.pop(0)
            for x_d, y_d in d:
                x, y = i + x_d, j + y_d
                if (0 <= x < lenght) and (0 <= y < lenght) and (grid[x][y] == 0):
                    grid[x][y] = 1
                    plan.append((x, y, result + 1))
        if result != 0:
            answer = result
        else:
            answer = -1
 
        return answer