結果

問題 No.367 ナイトの転身
ユーザー 👑 rin204
提出日時 2022-11-03 01:03:19
言語 PyPy3
(7.3.15)
結果
AC  
実行時間 200 ms / 2,000 ms
コード長 1,140 bytes
コンパイル時間 487 ms
コンパイル使用メモリ 82,276 KB
実行使用メモリ 85,844 KB
最終ジャッジ日時 2024-07-17 12:38:00
合計ジャッジ時間 3,808 ms
ジャッジサーバーID
(参考情報)
judge1 / judge2
このコードへのチャレンジ
(要ログイン)
ファイルパターン 結果
other AC * 27
権限があれば一括ダウンロードができます

ソースコード

diff #

from collections import deque

h, w = map(int, input().split())
S = [input() for _ in range(h)]
inf = 1 << 60
dist = [inf] * (h * w * 2)

def f(i, j, t):
    return (i * w + j) * 2 + t

directions = []
directions.append([])
for i in [-2, -1, 1, 2]:
    for j in [-2, -1, 1, 2]:
        if abs(i) != abs(j):
            directions[0].append((i, j))
directions.append(((1, 1), (1, -1), (-1, 1), (-1, -1)))

for i in range(h):
    for j in range(w):
        if S[i][j] == "S":
            si = i
            sj = j
        elif S[i][j] == "G":
            gi = i
            gj = j

queue = deque()
dist[f(si, sj, 0)] = 0
queue.append((si, sj, 0))
while queue:
    i, j, t = queue.popleft()
    for di, dj in directions[t]:
        ni = i + di
        nj = j + dj
        if ni < 0 or ni >= h or nj < 0 or nj >= w:
            continue
        if S[ni][nj] == "R":
            nt = t ^ 1
        else:
            nt = t
        if dist[f(ni, nj, nt)] == inf:
            dist[f(ni, nj, nt)] = dist[f(i, j, t)] + 1
            queue.append((ni, nj, nt))

ans = min(dist[f(gi, gj, 0)], dist[f(gi, gj, 1)])
if ans == inf:
    ans = -1
print(ans)
0