結果

問題 No.3199 Key-Door Grid
ユーザー 👑 SPD_9X2
提出日時 2025-07-12 03:39:09
言語 PyPy3
(7.3.15)
結果
AC  
実行時間 877 ms / 3,000 ms
コード長 1,436 bytes
コンパイル時間 391 ms
コンパイル使用メモリ 81,904 KB
実行使用メモリ 171,480 KB
最終ジャッジ日時 2025-07-12 03:39:25
合計ジャッジ時間 15,199 ms
ジャッジサーバーID
(参考情報)
judge3 / judge2
このコードへのチャレンジ
(要ログイン)
ファイルパターン 結果
sample AC * 3
other AC * 37
権限があれば一括ダウンロードができます

ソースコード

diff #

H,W,M = map(int,input().split())

S = [ input() for i in range(H) ]

INF = float("inf")

dp = [ [ [INF] * 10 for j in range(W)] for i in range(H)]

st = None
go = None
for i in range(H):
    for j in range(W):
        if S[i][j] == "S":
            st = (i,j)
        if S[i][j] == "G":
            go = (i,j)

from collections import deque
q = deque()

dp[st[0]][st[1]][0] = 0
q.append( (st[0],st[1],0) )

while q:

    x,y,z = q.popleft()
    cost = dp[x][y][z] + 1
    
    for i,j in ( (x-1,y),(x+1,y),(x,y-1),(x,y+1) ):

        if not ( 0 <= i < H and 0 <= j < W ):
            continue
        
        elif S[i][j] == "#":
            pass

        elif S[i][j] == "." or S[i][j] == "G" or S[i][j] == "S":
            if dp[i][j][z] > cost:
                dp[i][j][z] = cost
                q.append( (i,j,z) )

            if S[i][j] == "G":
                break

        elif "1" <= S[i][j] <= "9":
            k = int(S[i][j])
            if dp[i][j][k] > cost:
                dp[i][j][k] = cost
                q.append( (i,j,k) )

        elif "a" <= S[i][j] <= "i":
            k = ord(S[i][j]) - ord("a") + 1
            if z == k and dp[i][j][k] > cost:
                dp[i][j][k] = cost
                q.append( (i,j,k) )

#for k in range(10):
#   for i in range(H):
#        print ( [ dp[i][j][k] for j in range(W) ] )
#    print ()

ans = min(dp[go[0]][go[1]])
if ans == INF:
    ans = -1

print (ans)
        
0