<문제 링크>
https://www.acmicpc.net/problem/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
|
import sys
from collections import deque
input = sys.stdin.readline
def bfs(m, n, ground):
directions = [(-1,0),(1,0),(0,-1),(0,1)] # 동서남북 방향벡터 정의
# 토마토 위치 = bfs 시작할 위치 저장
q = deque([(i, j) for i in range(m) for j in range(n) if ground[i][j] == 1])
while q:
x, y = q.popleft()
for dx, dy in directions:
nx, ny = x + dx, y + dy
if 0 <= nx < m and 0 <= ny < n and ground[nx][ny] == 0:
ground[nx][ny] = ground[x][y] + 1
q.append((nx, ny))
def calculate_days(m, n, ground):
bfs(m, n, ground)
max_days = 0
# 모든 셀이 업데이트 되었는지 확인
for row in ground:
for v in row:
if v == 0:
return -1
max_days = max(max_days, v)
return max_days - 1
n, m = map(int, input().split())
ground = [list(map(int, input().split())) for _ in range(m)]
result = calculate_days(m, n, ground)
print(result)
|
cs |
처음에 DFS로 시도했는데, 토마토가 익어가는건 깊이 우선이 아니라 너비 우선이기 때문에 BFS로 풀어야 한다.
복잡한 문제로 보이지만, BFS를 이해하고 차근차근 풀면 이해할 수 있는 문제였다.
'프로그래밍 > Python' 카테고리의 다른 글
백준_python 16953번 A → B (BFS, 그래프 깊이) (1) | 2024.05.20 |
---|---|
백준_python 2468번 안전 영역 (BFS, DFS, 부르트포스 그래프) (0) | 2024.05.13 |
백준_python 11659번 구간 합 구하기 4 (누적합, 시간초과) (0) | 2024.04.27 |
백준_python 9375번 패션왕 신해빈(딕셔너리) (1) | 2024.04.26 |
정규표현식_python 단어만 남기고 비단어 문자 제거 (0) | 2024.04.25 |