问题描述
小强在玩一个走迷宫的游戏,他操控的人物现在位于迷宫的起点,他的目标是尽快的达到终点。每一次他可以选择花费一个时间单位向上或者向下或者向左或者向右走一格,或是使用自己的对称飞行器花费一个时间单位瞬移到关于当前自己点中心对称的格子,且每一次移动的目的地不能存在障碍物。具体来数说,设当前迷宫有 n n n行 m m m列,如果当前小强操控的人物位于点 A ( x , y ) A(x, y) A(x,y),那么关于点 A A A中心对称的格子 B ( x ′ , y ′ ) B(x', y') B(x′,y′)满足 x + x ′ = n + 1 x + x' = n + 1 x+x′=n+1且 y + y ′ = m + 1 y + y' = m + 1 y+y′=m+1。需要注意的是,对称飞行器最多使用5次。
问题分析
典型的搜索问题,在考虑中心对称的情况下,使用bfs或者dfs即可解决。
代码示例
from collections import deque
n, m = map(int, input().split(' '))
matrix = []
for i in range(n):
matrix.append(list(input()))
si, sj = 0, 0
is_found = False
for i in range(n):
for j in range(m):
if matrix[i][j] == 'S':
si = i
sj = j
is_found = True
break
if is_found:
break
directions = [(1, 0), (0, -1), (-1, 0), (0, 1)] # 上下左右
# bfs
queue = deque()
queue.appendleft((si, sj, 5, 0))
while queue:
row, col, cnt, step = queue.pop()
if matrix[row][col] == 'E':
break
matrix[row][col] = '#'
if 0 <= row + 1 < n and matrix[row + 1][col] != '#':
queue.appendleft((row + 1, col, cnt, step + 1))
if 0 <= col - 1 < m and matrix[row][col - 1] != '#':
queue.appendleft((row, col - 1, cnt, step + 1))
if 0 <= row -1 < n and matrix[row - 1][col] != '#':
queue.appendleft((row - 1, col, cnt, step + 1))
if 0 <= col + 1 < m and matrix[row][col + 1] != '#':
queue.appendleft((row, col + 1, cnt, step + 1))
if matrix[n - 1 - row][m - 1 - col] != '#' and 0 <= cnt:
queue.appendleft((n - 1 - row, m - 1 - col, cnt - 1, step + 1))
print(step)