結果

問題 No.340 雪の足跡
ユーザー gew1fw
提出日時 2025-06-12 21:01:50
言語 PyPy3
(7.3.15)
結果
TLE  
実行時間 -
コード長 2,359 bytes
コンパイル時間 263 ms
コンパイル使用メモリ 82,096 KB
実行使用メモリ 181,512 KB
最終ジャッジ日時 2025-06-12 21:04:33
合計ジャッジ時間 10,415 ms
ジャッジサーバーID
(参考情報)
judge5 / judge4
このコードへのチャレンジ
(要ログイン)
ファイルパターン 結果
sample AC * 5
other AC * 12 TLE * 4 -- * 16
権限があれば一括ダウンロードができます

ソースコード

diff #

import sys
from collections import deque

def get_coords(b, W):
    x = b % W
    y = b // W
    return x, y

def get_b(x, y, W):
    return x + y * W

def get_path(prev_b, current_b, W):
    x1, y1 = get_coords(prev_b, W)
    x2, y2 = get_coords(current_b, W)
    path = []
    if x1 == x2:
        # 同一列,移动南北
        if y2 > y1:
            dy = 1
        else:
            dy = -1
        y = y1
        while y != y2:
            path.append((x1, y))
            y += dy
        path.append((x1, y))
    elif y1 == y2:
        # 同一行,移动东西
        if x2 > x1:
            dx = 1
        else:
            dx = -1
        x = x1
        while x != x2:
            path.append((x, y1))
            x += dx
        path.append((x, y1))
    else:
        return []
    # 转换为区画号
    path_b = [get_b(x, y, W) for (x, y) in path]
    return path_b

def main():
    input = sys.stdin.read().split()
    ptr = 0
    W = int(input[ptr])
    ptr += 1
    H = int(input[ptr])
    ptr += 1
    N = int(input[ptr])
    ptr += 1
    max_b = W * H - 1
    graph = [[] for _ in range(max_b + 1)]
    edges = set()
    for _ in range(N):
        M_i = int(input[ptr])
        ptr += 1
        B_path = list(map(int, input[ptr:ptr+M_i+1]))
        ptr += M_i + 1
        for j in range(M_i):
            prev_b = B_path[j]
            current_b = B_path[j+1]
            path = get_path(prev_b, current_b, W)
            for i in range(len(path) - 1):
                u = path[i]
                v = path[i+1]
                if u == v:
                    continue
                if u < v:
                    edge = (u, v)
                else:
                    edge = (v, u)
                if edge not in edges:
                    edges.add(edge)
                    graph[u].append(v)
                    graph[v].append(u)
    # BFS
    start = 0
    end = max_b
    if start == end:
        print(0)
        return
    distance = [-1] * (max_b + 1)
    distance[start] = 0
    q = deque()
    q.append(start)
    while q:
        u = q.popleft()
        if u == end:
            print(distance[u])
            return
        for v in graph[u]:
            if distance[v] == -1:
                distance[v] = distance[u] + 1
                q.append(v)
    print("Odekakedekinai..")

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