結果

問題 No.367 ナイトの転身
ユーザー rlangevin
提出日時 2023-09-04 12:04:26
言語 PyPy3
(7.3.15)
結果
AC  
実行時間 405 ms / 2,000 ms
コード長 1,508 bytes
コンパイル時間 315 ms
コンパイル使用メモリ 82,456 KB
実行使用メモリ 158,032 KB
最終ジャッジ日時 2024-06-22 10:47:48
合計ジャッジ時間 4,524 ms
ジャッジサーバーID
(参考情報)
judge3 / judge2
このコードへのチャレンジ
(要ログイン)
ファイルパターン 結果
other AC * 27
権限があれば一括ダウンロードができます

ソースコード

diff #

from collections import deque
inf = 10 ** 18
def bfs(G, s, N):
    Q = deque([])
    dist = [inf] * N
    par = [inf] * N
    dist[s] = 0
    for u in G[s]:
        par[u] = s
        dist[u] = 1
        Q.append(u)

    while Q:
        u = Q.popleft()
        for v in G[u]:
            if dist[v] != inf:
                continue
            dist[v] = dist[u] + 1
            par[v] = u
            Q.append(v)
            
    return dist

H, W = map(int, input().split())
G = []
sx, sy, gx, gy = -1, -1, -1, -1
for i in range(H):
    s = list(input())
    for j in range(W):
        if s[j] == "S":
            sx, sy = i, j
        if s[j] == "G":
            gx, gy = i, j
    G.append(s)

dx = [[1, 1, 2, 2, -1, -1, -2, -2], [1, 1, -1, -1]]
dy = [[2, -2, 1, -1, 2, -2, 1, -1], [1, -1, 1, -1]]
K = [8, 4]

N = 2 * H * W
GG = [[] for i in range(N)]
def f(n, i, j):
    return n * H * W + i * W + j

for i in range(H):
    for j in range(W):
        for n in range(2):
            for k in range(K[n]):
                x = i + dx[n][k]
                y = j + dy[n][k]
                if x < 0 or x > H - 1 or y < 0 or y > W - 1:
                    continue
                if G[x][y] == "R":
                    nn = 1 - n
                else:
                    nn = n
                now = f(n, i, j)
                nex = f(nn, x, y)
                GG[now].append(nex)
            

D = bfs(GG, f(0, sx, sy), N)
ans = min(D[f(0, gx, gy)], D[f(1, gx, gy)])
print(ans) if ans != inf else print(-1)
0