[백준] 7576번 토마토 (파이썬)

dongEon·2023년 4월 10일
0

난이도 : GOLD V

문제링크 : https://www.acmicpc.net/problem/7569

문제해결 아이디어

  • 평범한 BFS 문제.
  • visited를 갱신할때 +1 더해가면서 날짜계산을 했다.
  • 마지막에 안익은 토마토 있는지 확인하고 정답을 리턴.

소스코드

import sys
from collections import deque
import copy

def bfs():
    while q:
        x,y = q.popleft()

        for k in range(4):
            nx = x + dx[k]
            ny = y + dy[k]

            if 0 <= nx < n and 0 <= ny < m and not visited[nx][ny]:
                q.append((nx, ny))
                visited[nx][ny] = visited[x][y] + 1

input = sys.stdin.readline

m, n = map(int, input().split())

dx = [0,0,-1,1]
dy = [1,-1,0,0]
res = 0
graph = []

for _ in range(n):
    graph.append(list(map(int, input().split())))

visited = copy.deepcopy(graph)

q = deque()

for i in range(n):
    for j in range(m):
        if graph[i][j] == 1:
            q.append((i,j))
bfs()

for i in visited:
    for j in i:
        if j == 0:
            print(-1)
            exit(0)
    res = max(res, max(i))
print(res - 1)
profile
개발 중에 마주한 문제와 해결 과정, 새롭게 배운 지식, 그리고 알고리즘 문제 해결에 대한 다양한 인사이트를 공유하는 기술 블로그입니다

0개의 댓글