結果

問題 No.367 ナイトの転身
ユーザー chocorusk
提出日時 2020-09-26 04:05:03
言語 PyPy3
(7.3.15)
結果
AC  
実行時間 236 ms / 2,000 ms
コード長 1,371 bytes
コンパイル時間 170 ms
コンパイル使用メモリ 81,920 KB
実行使用メモリ 84,996 KB
最終ジャッジ日時 2024-06-28 13:22:16
合計ジャッジ時間 3,831 ms
ジャッジサーバーID
(参考情報)
judge3 / judge4
このコードへのチャレンジ
(要ログイン)
ファイルパターン 結果
other AC * 27
権限があれば一括ダウンロードができます

ソースコード

diff #

import sys
read=sys.stdin.buffer.read
readline=sys.stdin.buffer.readline
readlines=sys.stdin.buffer.readlines

h, w=map(int, readline().split())
s=read().decode().split()
sx, sy, gx, gy=0, 0, 0, 0
for i, si in enumerate(s):
    j=si.find('S')
    if j>=0:sx, sy=i, j
    j=si.find('G')
    if j>=0:gx, gy=i, j
INF=10**9
d=[[INF]*(h*w) for _ in range(2)]
d[0][sx*w+sy]=0
from collections import deque
que=deque()
que.append((sx*w+sy, 0))
dn=[(1, 2), (2, 1)]
db=[(1, 1), (1, -1), (-1, 1), (-1, -1)]
while que:
    p, t=que.popleft()
    x, y=divmod(p, w)
    if t==0:
        for dx, dy in dn:
            for px, py in db:
                x1, y1, t1=x+dx*px, y+dy*py, t
                if x1<0 or x1>=h or y1<0 or y1>=w:
                    continue
                if s[x1][y1]=='R':
                    t1=1
                p1=x1*w+y1
                if d[t1][p1]>d[t][p]+1:
                    d[t1][p1]=d[t][p]+1
                    que.append((p1, t1))
    else:
        for dx, dy in db:
            x1, y1, t1=x+dx, y+dy, t
            if x1<0 or x1>=h or y1<0 or y1>=w:
                continue
            if s[x1][y1]=='R':
                t1=0
            p1=x1*w+y1
            if d[t1][p1]>d[t][p]+1:
                d[t1][p1]=d[t][p]+1
                que.append((p1, t1))
ans=min(d[0][gx*w+gy], d[1][gx*w+gy])
if ans==INF:
    print(-1)
else:
    print(ans)
0