- [Leetcode 3552. Grid Teleportation Traversal](#Leetcode 3552. Grid Teleportation Traversal)
- [1. 解题思路](#1. 解题思路)
- [2. 代码实现](#2. 代码实现)
1. 解题思路
这一题的话核心就是一个广度优先遍历,我们只需要从原点开始,一点点考察其所能到达的位置,直至其最终到达终点即可。
唯一特殊的是,考虑到传送的存在,这里会有些特殊操作,不难发现,一个端口至多发生一次传送,否则必然可以优化路线,因此我们只需要考察每一个端口值上是否有过传送即可。
2. 代码实现
给出python代码实现如下:
python
class Solution:
def minMoves(self, matrix: List[str]) -> int:
n, m = len(matrix), len(matrix[0])
teleportation = defaultdict(list)
for i in range(n):
for j in range(m):
if matrix[i][j] in "#.":
continue
teleportation[matrix[i][j]].append((i, j))
seen = {(0, 0)}
q = [(0, 0, 0, 0)]
def add_teleportation(step, i, j, status):
nonlocal seen, q
if matrix[i][j] not in "#." and (status & (1 << (ord(matrix[i][j]) - ord('A'))) == 0):
for ti, tj in teleportation[matrix[i][j]]:
if (ti, tj) not in seen:
heapq.heappush(q, (step, ti, tj, status | (1 << (ord(matrix[i][j]) - ord('A')))))
seen.add((ti, tj))
return
add_teleportation(0, 0, 0, 0)
while q != []:
step, i, j, status = heapq.heappop(q)
if (i, j) == (n-1, m-1):
return step
if i+1 < n and (i+1, j) not in seen and matrix[i+1][j] != "#":
heapq.heappush(q, (step+1, i+1, j, status))
seen.add((i+1, j))
add_teleportation(step+1, i+1, j, status)
if j+1 < m and (i, j+1 ) not in seen and matrix[i][j+1] != "#":
heapq.heappush(q, (step+1, i, j+1, status))
seen.add((i, j+1))
add_teleportation(step+1, i, j+1, status)
if i-1 >= 0 and (i-1, j) not in seen and matrix[i-1][j] != "#":
heapq.heappush(q, (step+1, i-1, j, status))
seen.add((i-1, j))
add_teleportation(step+1, i-1, j, status)
if j-1 >= 0 and (i, j-1 ) not in seen and matrix[i][j-1] != "#":
heapq.heappush(q, (step+1, i, j-1, status))
seen.add((i, j-1))
add_teleportation(step+1, i, j-1, status)
return -1
提交代码评测得到:耗时6943ms,占用内存147.7MB。