結果

問題 No.367 ナイトの転身
ユーザー maspy
提出日時 2020-03-19 13:29:48
言語 PyPy3
(7.3.15)
結果
AC  
実行時間 400 ms / 2,000 ms
コード長 1,427 bytes
コンパイル時間 440 ms
コンパイル使用メモリ 82,264 KB
実行使用メモリ 147,768 KB
最終ジャッジ日時 2024-12-14 03:08:31
合計ジャッジ時間 4,258 ms
ジャッジサーバーID
(参考情報)
judge5 / judge3
このコードへのチャレンジ
(要ログイン)
ファイルパターン 結果
other AC * 27
権限があれば一括ダウンロードができます

ソースコード

diff #

#!/usr/bin/ python3.8
import sys
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines
import itertools
from collections import deque

H, W = map(int, readline().split())
S = ''.join(read().decode().split())

start = S.index('S')
goal = S.index('G')
N = H * W

Knight = ((2, 1), (1, 2), (-1, 2), (-2, 1), (-2, -1), (-1, -2), (1, -2), (2, -1))
Bishop = ((1, 1), (-1, 1), (-1, -1), (1, -1))

# 0 <= i < N:knightで出発
# N <= i < 2N:bishopで出発

graph = [[] for _ in range(N + N)]
for x, y in itertools.product(range(H), range(W)):
    for dx, dy in Knight:
        x1 = x + dx
        y1 = y + dy
        if not ((0 <= x1 < H) and (0 <= y1 < W)):
            continue
        i = x * W + y
        j = x1 * W + y1
        if S[j] == 'R':
            j += N
        graph[i].append(j)
    for dx, dy in Bishop:
        x1 = x + dx
        y1 = y + dy
        if not ((0 <= x1 < H) and (0 <= y1 < W)):
            continue
        i = x * W + y + N
        j = x1 * W + y1
        if S[j] != 'R':
            j += N
        graph[i].append(j)


INF = 10 ** 6
dist = [INF] * (N + N)
dist[start] = 0
q = deque([start])

while q:
    v = q.popleft()
    dw = dist[v] + 1
    for w in graph[v]:
        if dist[w] <= dw:
            continue
        dist[w] = dw
        q.append(w)

answer = min(dist[goal], dist[goal + N])
if answer == INF:
    answer = -1
print(answer)
0