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))
来源:oschina
链接:https://my.oschina.net/u/4375351/blog/3229008