fire map

别说谁变了你拦得住时间么 提交于 2020-04-11 11:45:17
import collections

class Solution(object):
    def minDist(self, arr, start_row, start_rol, end_row, end_col):
        """
        :type M: List[List[int]]
        :rtype: int
        """
        ans = self.bfs(arr, start_row, start_rol, end_row, end_col)
        row, col = len(arr), len(arr[0])
        for i in range(row):
            for j in range(col):
                if arr[i][j] == 1:
                    arr[i][j] = 0
                    dist = self.bfs(arr, start_row, start_rol, end_row, end_col)
                    if ans > 0 and dist > 0:
                        ans = min(dist, ans)
                    else:
                        ans = max(dist, ans)
                    arr[i][j] = 1
        return ans

    def bfs(self, arr, start_row, start_col, end_row, end_col):
        visted = set((start_row, start_col))
        R, C = len(arr), len(arr[0])
        dist = 0
        end = (end_row, end_col)
        q = collections.deque([(start_row, start_col)])
        while q:
            q2 = collections.deque()
            for node in q:
                if node == end:
                    return dist
                for l, r in [(-1, 0), (1, 0), (0, 1), (0, -1)]:
                    i, j = node[0]+l, node[1]+r
                    if i >= 0 and i < R and j >= 0 and j < C and \
                            arr[i][j] == 0 and (i, j) not in visted:
                        q2.append((i, j))
                        visted.add((i,j))
            dist += 1
            q = q2
        return -1


firemap = [[0,0,1,0], [1,0,0,0]]
# firemap = [[0,1,1,0], [1,0,0,0]]
firemap = [[0,1,1,0], [1,1,0,0]]
startCol, startRow = 0, 0
endCol, endRow = 3, 0
print(Solution().minDist(firemap, startRow, startCol, endRow, endCol))

  

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!