1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37
| from collections import deque
y_, x_ = map(int, input().split()) maze = [list(input()) for _ in range(y_)]
qList = [(0, 0, 0, 4, 1), (0, 0, 0, 3, 1), (0, 0, 0, 2, 1), (0, 0, 0, 1, 1), (0, 0, 0, 0, 1)] direction5 = [[(-1, 0), (0, 1), (0, -1)], [(1, 0), (0, 1), (0, -1)], [(1, 0), (-1, 0), (0, 1)], [(1, 0), (-1, 0), (0, -1)], [(1, 0), (-1, 0), (0, 1), (0, -1)]]
def bfs(): visited = [[[False] * 2 for _ in range(x_)] for _ in range(y_)] q = deque(qList) while q: x0, y0, d, dI, throughAb = q.popleft() if visited[y0][x0][throughAb]: continue visited[y0][x0][throughAb] = True
for dx, dy in direction5[dI]: nx, ny = x0 + dx, y0 + dy if 0 <= nx < x_ and 0 <= ny < y_: if nx == x_ - 1 and ny == y_ - 1: if maze[ny][nx] == '.' or (maze[ny][nx] == 'X' and throughAb == 1): return d + 1 if maze[ny][nx] == '.' and not visited[ny][nx][throughAb]: q.append((nx, ny, d + 1, dI, throughAb)) elif maze[ny][nx] == 'X' and throughAb == 1 and not visited[ny][nx][0]: q.append((nx, ny, d + 1, dI, 0)) return -1
print(bfs())
|