結果

問題 No.367 ナイトの転身
ユーザー rlangevinrlangevin
提出日時 2023-09-04 12:04:26
言語 PyPy3
(7.3.15)
結果
AC  
実行時間 509 ms / 2,000 ms
コード長 1,508 bytes
コンパイル時間 1,023 ms
コンパイル使用メモリ 87,208 KB
実行使用メモリ 160,688 KB
最終ジャッジ日時 2023-09-04 12:04:34
合計ジャッジ時間 7,259 ms
ジャッジサーバーID
(参考情報)
judge15 / judge12
このコードへのチャレンジ
(要ログイン)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 98 ms
71,500 KB
testcase_01 AC 95 ms
71,528 KB
testcase_02 AC 98 ms
71,496 KB
testcase_03 AC 98 ms
71,540 KB
testcase_04 AC 97 ms
71,464 KB
testcase_05 AC 96 ms
71,712 KB
testcase_06 AC 116 ms
77,460 KB
testcase_07 AC 97 ms
71,496 KB
testcase_08 AC 96 ms
71,688 KB
testcase_09 AC 96 ms
71,684 KB
testcase_10 AC 454 ms
159,072 KB
testcase_11 AC 509 ms
160,688 KB
testcase_12 AC 294 ms
109,324 KB
testcase_13 AC 283 ms
109,824 KB
testcase_14 AC 286 ms
108,132 KB
testcase_15 AC 131 ms
77,372 KB
testcase_16 AC 285 ms
105,288 KB
testcase_17 AC 150 ms
81,244 KB
testcase_18 AC 160 ms
82,452 KB
testcase_19 AC 177 ms
84,232 KB
testcase_20 AC 154 ms
81,568 KB
testcase_21 AC 177 ms
84,184 KB
testcase_22 AC 115 ms
77,364 KB
testcase_23 AC 130 ms
78,644 KB
testcase_24 AC 130 ms
77,972 KB
testcase_25 AC 126 ms
77,980 KB
testcase_26 AC 118 ms
77,580 KB
権限があれば一括ダウンロードができます

ソースコード

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