ps | |
---|---|
링크 | acmicpc.net/… |
출처 | BOJ |
문제 번호 | 7569 |
문제명 | 토마토 |
레벨 | 실버 1 |
분류 |
BFS |
시간복잡도 | O(MNH) |
인풋사이즈 | M<=100, N<=100, H<=100 |
사용한 언어 | Python |
제출기록 | 131588KB / 3236ms |
최고기록 | 1304ms |
해결날짜 | 2021/07/22 |
"""Solution code for "BOJ 7576. 토마토".
- Problem link: https://www.acmicpc.net/problem/7576
- Solution link: http://www.teferi.net/ps/problems/boj/7576
Tags: [BFS]
"""
from teflib import search
RIPE = '1'
UNRIPE = '0'
EMPTY = '-1'
def main():
def adj_tomatoes(cur_pos):
p, x = divmod(cur_pos, M)
z, y = divmod(p, N)
delta = 1
for coord_i, size_i in ((x, M), (y, N), (z, H)):
if coord_i > 0:
next_pos = cur_pos - delta
if tomatoes[next_pos] == UNRIPE:
yield next_pos
if coord_i < size_i - 1:
next_pos = cur_pos + delta
if tomatoes[next_pos] == UNRIPE:
yield next_pos
delta *= size_i
M, N, H = [int(x) for x in input().split()]
tomatoes = []
for _ in range(N * H):
tomatoes.extend(input().split())
ripe_tomatoes = [i for i, tom in enumerate(tomatoes) if tom == RIPE]
tomato_count = sum(1 for tom in tomatoes if tom != EMPTY)
dists = search.min_distances(adj_tomatoes, ripe_tomatoes)
print(-1 if len(dists) < tomato_count else max(dists.values()))
if __name__ == '__main__':
main()