ps | |
---|---|
링크 | acmicpc.net/… |
출처 | BOJ |
문제 번호 | 17114 |
문제명 | 하이퍼 토마토 |
레벨 | 골드 1 |
분류 |
BFS |
시간복잡도 | O(n) |
인풋사이즈 | n <= 10^6 |
사용한 언어 | Python |
제출기록 | 156628KB / 3760ms |
최고기록 | 3328ms |
해결날짜 | 2021/07/22 |
"""Solution code for "BOJ 17114. 하이퍼 토마토".
- Problem link: https://www.acmicpc.net/problem/17114
- Solution link: http://www.teferi.net/ps/problems/boj/17114
Tags: [BFS]
"""
import functools
import operator
import sys
from teflib import search
EMPTY = '-1'
RIPE = '1'
UNRIPE = '0'
def main():
def adj_tomatoes(pos):
p = pos
delta = 1
for size_i in sizes:
p, coord_i = divmod(p, size_i)
if coord_i > 0:
next_pos = pos - delta
if tomatoes[next_pos] == UNRIPE:
yield next_pos
if coord_i < size_i - 1:
next_pos = pos + delta
if tomatoes[next_pos] == UNRIPE:
yield next_pos
delta *= size_i
sizes = [int(x) for x in sys.stdin.readline().split()]
line_count = functools.reduce(operator.mul, sizes[1:])
tomatoes = []
for _ in range(line_count):
tomatoes.extend(sys.stdin.readline().split())
ripe_tomatoes = [i for i, x in enumerate(tomatoes) if x == RIPE]
tomato_count = sum(1 for x in tomatoes if x != EMPTY)
dists = search.min_distances(adj_tomatoes, ripe_tomatoes)
print(-1 if len(dists) < tomato_count else max(dists.values(), default=0))
if __name__ == '__main__':
main()