結果
| 問題 |
No.367 ナイトの転身
|
| コンテスト | |
| ユーザー |
|
| 提出日時 | 2016-05-28 10:11:58 |
| 言語 | PyPy3 (7.3.15) |
| 結果 |
AC
|
| 実行時間 | 227 ms / 2,000 ms |
| コード長 | 1,800 bytes |
| コンパイル時間 | 262 ms |
| コンパイル使用メモリ | 82,764 KB |
| 実行使用メモリ | 82,068 KB |
| 最終ジャッジ日時 | 2024-10-07 17:17:31 |
| 合計ジャッジ時間 | 3,044 ms |
|
ジャッジサーバーID (参考情報) |
judge3 / judge2 |
(要ログイン)
| ファイルパターン | 結果 |
|---|---|
| other | AC * 27 |
ソースコード
def read_data():
H, W = map(int, input().split())
s = [input() for i in range(H)]
return H, W, s
def parse_board(H, W, s):
reds = [False] * (H * W)
start = -1
goal = -1
for h in range(H):
sh = s[h]
for w in range(W):
c = sh[w]
if c == 'S':
start = h * W + w
elif c == 'G':
goal = h * W + w
elif c == 'R':
reds[h * W + w] = True
return reds, start, goal
def solve(H, W, s):
next_move = [(), ()]
next_move[0] = ((-2, -1), (-2, 1), (-1, -2), (-1, 2), (1, -2), (1, 2), (2, -1), (2, 1))
next_move[1] = ((-1, -1), (-1, 1), (1, -1), (1, 1))
reds, start, goal = parse_board(H, W, s)
return wfs(start, goal, reds, H, W, next_move)
def wfs(start, goal, reds, H, W, next_move):
HW = H * W
dist = [-1] * (HW * 2)
goals = [goal, goal + HW]
steps = 0
state = 0
frontiers = [start]
dist[start] = 0
while frontiers:
steps += 1
new_frontiers = []
for spos in frontiers:
state, pos = divmod(spos, HW)
h, w = divmod(pos, W)
for dh, dw in next_move[state]:
nh = h + dh
nw = w + dw
if 0 <= nh < H and 0 <= nw < W:
npos = nh * W + nw
new_state = 1 - state if reds[npos] else state
nspos = new_state * HW + npos
if dist[nspos] == -1:
dist[nspos] = steps
new_frontiers.append(nspos)
if nspos in goals:
return steps
frontiers = new_frontiers
return -1
if __name__ == '__main__':
pars = read_data()
print(solve(*pars))