목차

할로윈 묘지

ps
링크acmicpc.net/…
출처BOJ
문제 번호3860
문제명할로윈 묘지
레벨플래티넘 5
분류

SPFA

시간복잡도O(W^2*H^2)
인풋사이즈W<=30, H<=30
사용한 언어Python
제출기록35132KB / 1452ms
최고기록624ms
해결날짜2021/09/23

풀이

코드

"""Solution code for "BOJ 3860. 할로윈 묘지".

- Problem link: https://www.acmicpc.net/problem/3860
- Solution link: http://www.teferi.net/ps/problems/boj/3860

Tags: [SPFA]
"""

import sys
from teflib import tgraph

INF = float('inf')


def main():
    while True:
        W, H = [int(x) for x in sys.stdin.readline().split()]
        if W == H == 0:
            break

        G = int(sys.stdin.readline())
        graves = set()
        for _ in range(G):
            X, Y = [int(x) for x in sys.stdin.readline().split()]
            graves.add(Y * W + X)

        wgraph = [{} for _ in range(W * H)]
        E = int(sys.stdin.readline())
        for _ in range(E):
            X1, Y1, X2, Y2, T = [int(x) for x in sys.stdin.readline().split()]
            source, dest = Y1 * W + X1, Y2 * W + X2
            wgraph[source][dest] = T

        for source, edges in enumerate(wgraph):
            if wgraph[source]:  # haunted hole exists
                continue
            y, x = divmod(source, W)
            for dx, dy in [(-1, 0), (0, -1), (1, 0), (0, 1)]:
                nx, ny = x + dx, y + dy
                dest = ny * W + nx
                if 0 <= nx < W and 0 <= ny < H and dest not in graves:
                    edges[dest] = 1
        wgraph[W * H - 1].clear()

        dists = tgraph.spfa(wgraph, 0)
        if -INF in dists:
            print('Never')
        else:
            dist_to_dest = dists[W * H - 1]
            print('Impossible' if dist_to_dest == INF else dist_to_dest)


if __name__ == '__main__':
    main()