結果

問題 No.340 雪の足跡
ユーザー rpy3cpp
提出日時 2016-01-30 23:41:02
言語 Python3
(3.13.1 + numpy 2.2.1 + scipy 1.14.1)
結果
TLE  
実行時間 -
コード長 2,488 bytes
コンパイル時間 134 ms
コンパイル使用メモリ 12,800 KB
実行使用メモリ 105,956 KB
最終ジャッジ日時 2024-09-21 19:34:04
合計ジャッジ時間 18,420 ms
ジャッジサーバーID
(参考情報)
judge4 / judge1
このコードへのチャレンジ
(要ログイン)
ファイルパターン 結果
sample AC * 5
other AC * 24 TLE * 8
権限があれば一括ダウンロードができます

ソースコード

diff #

import sys
import itertools

def solve():
    W, H, hsWH, hsHW = read_data()
    hsWH = list(itertools.accumulate(hsWH))
    hsHW = list(itertools.accumulate(hsHW))
    result = wfs(W, H, hsWH, hsHW)
    return result


def read_data():
    W, H, N = map(int, input().split())
    hsWH = [0] * (W * H)  # vertical lines
    hsHW = [0] * (W * H)  # horizontal lines
    lines = sys.stdin.readlines()
    flag = True
    for line in lines:
        flag = not flag
        if flag:
            Bs = list(map(int, line.split()))
            h0, w0 = divmod(Bs[0], W)
            for b in Bs:
                h1, w1 = divmod(b, W)
                if h0 == h1:  # horizontal move
                    if w0 > w1:
                        hsHW[b] += 1
                        hsHW[b + w0 - w1] -= 1
                    else:
                        hsHW[b + w0 - w1] += 1
                        hsHW[b] -= 1
                    w0 = w1
                else:        # vertical move
                    if h0 > h1:
                        hsWH[w1 * H + h1] += 1
                        hsWH[w1 * H + h0] -= 1
                    else:
                        hsWH[w1 * H + h0] += 1
                        hsWH[w1 * H + h1] -= 1
                    h0 = h1
    return W, H, hsWH, hsHW


def wfs(W, H, hsWH, hsHW):
    '''
    (0, 0) から (W-1, H-1) までの最短距離を求める。
    hsWH[w * H + h]: cell(w, h) と cell(w, h+1) に辺があるか否か
    hsHW[h * W + w]: cell(w, h) と cell(w+1, h) に辺があるか否か
    '''
    start = 0
    goal = H * W - 1
    unvisited = [True] * (H * W)
    frontiers = [start]
    cost = 0
    while frontiers:
        cost += 1
        new_frontiers = []
        for f in frontiers:
            if f == goal:
                return cost - 1
            g = (f % W) * H + (f//W)
            if hsWH[g] and unvisited[f + W]:
                unvisited[f + W] = False
                new_frontiers.append(f + W)
            if hsWH[g - 1] and unvisited[f - W]:
                unvisited[f - W] = False
                new_frontiers.append(f - W)
            if hsHW[f] and unvisited[f + 1]:
                unvisited[f + 1] = False
                new_frontiers.append(f + 1)
            if hsHW[f - 1] and unvisited[f - 1]:
                unvisited[f - 1] = False
                new_frontiers.append(f - 1)
        frontiers = new_frontiers
    return -1

ans = solve()
if ans == -1:
    print("Odekakedekinai..")
else:
    print(ans)
0