1. 문제
https://www.acmicpc.net/problem/7576
7576번: 토마토
첫 줄에는 상자의 크기를 나타내는 두 정수 M,N이 주어진다. M은 상자의 가로 칸의 수, N은 상자의 세로 칸의 수를 나타낸다. 단, 2 ≤ M,N ≤ 1,000 이다. 둘째 줄부터는 하나의 상자에 저장된 토마토
www.acmicpc.net
2. 풀이 과정
import sys
from collections import deque
input = sys.stdin.readline
n, m = map(int, input().split())
dx = [-1, 0, 1, 0]
dy = [0, 1, 0, -1]
q = deque()
graph = []
for i in range(m):
graph.append(list(map(int, input().split())))
for j in range(n):
if graph[i][j] == 1:
q.append((i, j))
def bfs(graph):
days = -1
while q:
days += 1
for _ in range(len(q)):#for문 안에 append가 적용되기 전의 q길이가 반환됨
x, y = q.popleft()
for i in range(4):
nx = x + dx[i]
ny = y + dy[i]
if 0<=nx<m and 0<=ny<n and graph[nx][ny]==0:
graph[nx][ny] = graph[x][y]+1
q.append((nx, ny))
for k in graph:#행을 하나씩 반환
if 0 in k : return -1
return days
print(bfs(graph))
'코딩문제풀이 > Baekjoon' 카테고리의 다른 글
[Python_DFS&BFS] 백준 1987번 : 알파벳 (0) | 2021.08.10 |
---|---|
[Python_DFS&BFS] 백준 14502번 : 연구소 (0) | 2021.08.09 |
[Python_DFS&BFS] 백준 2178번 : 미로 탐색 (0) | 2021.08.05 |
[Python_Greedy] 백준 1789번 : 수들의 합 (0) | 2021.08.04 |
[Python_Greedy] 백준 2217번 : 로프 (0) | 2021.08.03 |