단계별로 풀어보기 DFS와 BFS의 6단계 문제
7576번: 토마토
첫 줄에는 상자의 크기를 나타내는 두 정수 M,N이 주어진다. M은 상자의 가로 칸의 수, N은 상자의 세로 칸의 수를 나타낸다. 단, 2 ≤ M,N ≤ 1,000 이다. 둘째 줄부터는 하나의 상자에 저장된 토마토들의 정보가 주어진다. 즉, 둘째 줄부터 N개의 줄에는 상자에 담긴 토마토의 정보가 주어진다. 하나의 줄에는 상자 가로줄에 들어있는 토마토의 상태가 M개의 정수로 주어진다. 정수 1은 익은 토마토, 정수 0은 익지 않은 토마토, 정수 -1은 토마
www.acmicpc.net
한 시간 정도 걸렸던 것 같다.
최솟값을 구하는 거니까 BFS를 이용했다.
from sys import stdin
m, n = list(map(int, stdin.readline().split()))
matrix = []
count = 0
minus = 0
zero = 0
import collections
q = collections.deque()
one = []
for i in range(n):
temp = list(map(int, stdin.readline().split()))
matrix.append(temp)
count += temp.count(1)
minus += temp.count(-1)
zero += temp.count(0)
for j in range(m):
if temp[j] == 1:
q.append((i, j, 0))
if zero == 0:
print(0)
else:
ripen = 0
result = 0
visited = [[False] * m for i in range(n)]
while q:
cur = q.popleft()
if not visited[cur[0]][cur[1]]:
visited[cur[0]][cur[1]] = True
matrix[cur[0]][cur[1]] = 1
ripen += 1
result = cur[2]
else:
continue
if cur[0] + 1 < n and matrix[cur[0] + 1][cur[1]] == 0 and not visited[cur[0] + 1][cur[1]]:
q.append((cur[0] + 1, cur[1], cur[2] + 1))
if cur[1] + 1 < m and matrix[cur[0]][cur[1] + 1] == 0 and not visited[cur[0]][cur[1] + 1]:
q.append((cur[0], cur[1] + 1, cur[2] + 1))
if cur[0] - 1 >= 0 and matrix[cur[0] - 1][cur[1]] == 0 and not visited[cur[0] - 1][cur[1]]:
q.append((cur[0] - 1, cur[1], cur[2] + 1))
if cur[1] - 1 >= 0 and matrix[cur[0]][cur[1] - 1] == 0 and not visited[cur[0]][cur[1] - 1]:
q.append((cur[0], cur[1] - 1, cur[2] + 1))
if ripen == m * n - minus:
print(result)
else:
print(-1)
'알고리즘 문제' 카테고리의 다른 글
[백준] 1697 숨바꼭질 (0) | 2020.01.10 |
---|---|
[백준] 7569번 토마토 (0) | 2020.01.10 |
[백준] 2178번 미로 탐색 (0) | 2020.01.10 |
[백준] 1330번 두 수 비교하기 (0) | 2020.01.10 |
[백준] 1541번 잃어버린 괄호 (0) | 2020.01.10 |