Home (Python)[백준] 토마토_7576
Post
Cancel

(Python)[백준] 토마토_7576

7576번: 토마토

풀이


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
# bfs -> queue

# deque - 내부적으로 deque은 double-linked list로 구현되어 있음. 그래서 양 끝의 요소의 추가/삭제가 O(1)을 만족하게 됨
# <-> 리스트 - 리스트의 마지막 원소를 삭제는 O(1)이지만, 첫번째 원소를 삭제하면 삭제 후 모든 원소를 앞으로 이동시키기 때문에 시간 복잡도가 O(n)
from collections import deque

# 방향 벡터 정의
dx, dy = [-1, 1, 0, 0], [0, 0, -1, 1]

# 입력 받기
m, n = map(int, input().split())
graph = [list(map(int, input().split())) for _ in range(n)]

# 시작점 찾기와 BFS 함수 정의
def find_starting_points():
    queue = deque()
    for i in range(n):
        for j in range(m):
            if graph[i][j] == 1:
                queue.append([i, j])
    return queue

def bfs(queue):
    while queue:
        x, y = queue.popleft()
        for i in range(len(dx)):
            nx, ny = x + dx[i], y + dy[i]
            if 0 <= nx < n and 0 <= ny < m and graph[nx][ny] == 0:
                graph[nx][ny] = graph[x][y] + 1
                queue.append([nx, ny])

# 시작점 찾기
queue = find_starting_points()

# BFS 수행
bfs(queue)

anw = 0
for row in graph:
    for j in row:
        if j == 0:
            print(-1)
            exit(0)
    anw = max(anw, max(row))

print(anw - 1) # 처음 시작을 1로 했으니 -1
This post is licensed under CC BY 4.0 by the author.