输入:[[1,0,-1,1],[-2,0,-1,-3],[2,2,0,0]]输出:3解释:从-2起点先向上走到1,再通过传送门到达最右上角的1位置 再往下走到达-3终点
from typing import (
List,
)
from collections import deque
class Solution:
"""
@param maze_map: a 2D grid
@return: return the minium distance
"""
def get_min_distance(self, maze_map: List[List[int]]) -> int:
# write your code here
if not maze_map:
return 0
n,m = len(maze_map), len(maze_map[0])
q = deque()
directions = [(1,0),(0,1),(-1,0),(0,-1)]
distance = {}
num_dict = {}
for i in range(n):
for j in range(m):
if maze_map[i][j] == -2:
q.append((i,j))
distance[(i,j)] = 0
if maze_map[i][j] > 0:
if maze_map[i][j] not in num_dict:
num_dict[maze_map[i][j]] = []
num_dict[maze_map[i][j]].append((i,j))
while q:
x,y = q.popleft()
if maze_map[x][y] == -3:
return distance[(x,y)]
for dx,dy in directions:
nx,ny = x+dx,y+dy
if 0 <= nx < n and 0 <= ny < m and maze_map[nx][ny] != -1 and (nx,ny) not in distance:
distance[(nx,ny)] = distance[(x,y)] + 1
q.append((nx, ny))
if maze_map[x][y] > 0:
for nx,ny in num_dict[maze_map[x][y]]:
if (nx,ny) not in distance:
distance[(nx,ny)] = distance[(x,y)] + 1
q.append((nx, ny))
num_dict[maze_map[x][y]] = [] #防止重复处理
return -1