ps | |
---|---|
링크 | acmicpc.net/… |
출처 | BOJ |
문제 번호 | 7576 |
문제명 | 토마토 |
레벨 | 실버 1 |
분류 |
BFS |
시간복잡도 | O(M*N) |
인풋사이즈 | M<=1000, N<=1000 |
사용한 언어 | Python |
제출기록 | 134600KB / 2496ms |
최고기록 | 1064ms |
해결날짜 | 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):
y, x = divmod(cur_pos, M)
delta = 1
for coord_i, size_i in ((x, M), (y, N)):
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 = [int(x) for x in input().split()]
tomatoes = []
for _ in range(N):
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()