[leetcode]Shortest Distance from All Buildings

首先用flooding,暴力的多次bfs,差一点就要超时

 

from queue import Queue

class Solution:
    def markDistance(self, grid, i, j):
        m = len(grid)
        n = len(grid[0])
        distance = [[None] * n for k in range(m)]
        
        que = Queue()
        distance[i][j] = 0
        que.put((i, j))
        
        while not que.empty():
            x, y = que.get()
            current = distance[x][y]
            if grid[x][y] == 1 and current != 0:
                continue
            for dx, dy in [(0, 1), (0, -1), (1, 0), (-1, 0)]:
                if x + dx < 0 or x + dx >= m or y + dy < 0 or y + dy >= n:
                    continue
                if grid[x + dx][y + dy] == 2: # block
                    continue
                if distance[x + dx][y + dy] is not None: # already visited
                    continue
                distance[x + dx][y + dy] = current + 1
                que.put((x + dx, y + dy))
        
        return distance
    
    
    def shortestDistance(self, grid: List[List[int]]) -> int:
        if not len(grid) or not len(grid[0]):
            return -1
        m = len(grid)
        n = len(grid[0])
        
        buildings = []
        for i in range(m):
            for j in range(n):
                if grid[i][j] == 1:
                    buildings.append((i, j))
                    
        distances = [] # None for not visited, int for distances
        
        for building in buildings:
            distances.append(self.markDistance(grid, building[0], building[1]))
            
        result = -1
        for i in range(m):
            for j in range(n):
                current = 0
                for k in range(len(distances)):
                    if not distances[k][i][j]:
                        current = -1
                        break
                    else:
                        current += distances[k][i][j]
                if current != -1 and (result == -1 or result > current):
                    result = current
        
        return result

  

你可能感兴趣的:([leetcode]Shortest Distance from All Buildings)