結果

問題 No.367 ナイトの転身
ユーザー はむ吉🐹はむ吉🐹
提出日時 2016-05-01 20:06:01
言語 PyPy3
(7.3.15)
結果
AC  
実行時間 417 ms / 2,000 ms
コード長 1,776 bytes
コンパイル時間 217 ms
コンパイル使用メモリ 82,044 KB
実行使用メモリ 92,904 KB
最終ジャッジ日時 2024-10-05 00:48:39
合計ジャッジ時間 3,825 ms
ジャッジサーバーID
(参考情報)
judge2 / judge4
このコードへのチャレンジ
(要ログイン)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 41 ms
55,320 KB
testcase_01 AC 40 ms
55,468 KB
testcase_02 AC 40 ms
55,564 KB
testcase_03 AC 38 ms
54,956 KB
testcase_04 AC 38 ms
56,020 KB
testcase_05 AC 37 ms
55,876 KB
testcase_06 AC 56 ms
65,708 KB
testcase_07 AC 37 ms
55,304 KB
testcase_08 AC 41 ms
56,084 KB
testcase_09 AC 41 ms
54,720 KB
testcase_10 AC 248 ms
86,172 KB
testcase_11 AC 417 ms
92,904 KB
testcase_12 AC 126 ms
78,864 KB
testcase_13 AC 142 ms
79,904 KB
testcase_14 AC 204 ms
82,096 KB
testcase_15 AC 106 ms
77,532 KB
testcase_16 AC 203 ms
80,972 KB
testcase_17 AC 130 ms
77,916 KB
testcase_18 AC 129 ms
77,620 KB
testcase_19 AC 129 ms
78,152 KB
testcase_20 AC 86 ms
77,204 KB
testcase_21 AC 125 ms
77,836 KB
testcase_22 AC 46 ms
63,064 KB
testcase_23 AC 63 ms
74,080 KB
testcase_24 AC 91 ms
77,264 KB
testcase_25 AC 88 ms
77,072 KB
testcase_26 AC 71 ms
76,508 KB
権限があれば一括ダウンロードができます

ソースコード

diff #

#!/usr/bin/env pypy3

import array
import collections


DS_KNIGHT = [(1, 2), (-1, -2), (1, -2), (-1, 2), (2, 1), (-2, -1), (2, -1), (-2, 1)]
DS_MB = [(1, 1), (-1, -1), (1, -1), (-1, 1)]
INF = 10 ** 8
Status = collections.namedtuple("Status", "is_knight r c")


def min_num_of_operations(height, width, board, start, goal):
    s_start = Status(True, start[0], start[1])
    dist = [[array.array("L", (INF for _ in range(width))) for _ in range(height)] for _ in range(2)]
    dist[s_start.is_knight][s_start.r][s_start.c] = 0
    q = collections.deque()
    q.append(s_start)
    while q:
        s0 = q.popleft()
        if (s0.r, s0.c) == goal:
            break
        for dr, dc in (DS_KNIGHT if s0.is_knight else DS_MB):
            (r, c) = (s0.r + dr, s0.c + dc)
            if r < 0 or r >= height or c < 0 or c >= width:
                continue
            else:
                new_type = s0.is_knight ^ (board[r][c] == 'R')
                if dist[int(new_type)][r][c] >= INF:
                    s = Status(new_type, r, c)
                    q.append(s)
                    dist[int(new_type)][r][c] = dist[int(s0.is_knight)][s0.r][s0.c] + 1
    return min(dist[True][goal[0]][goal[1]], dist[False][goal[0]][goal[1]])


def main():
    height, width = map(int, input().split())
    board = []
    start = None
    goal = None
    for r in range(height):
        row = input()
        if start is None or goal is None:
            for c in range(width):
                if row[c] == "S":
                    start = (r, c)
                elif row[c] == "G":
                    goal = (r, c)
        board.append(row)
    ans = min_num_of_operations(height, width, board, start, goal)
    print(ans if ans < INF else -1)


if __name__ == '__main__':
    main()
0