https://www.acmicpc.net/problem/7576
그래프 표현 가능
그래프 탐색
3 | 4 | -1 | |
---|---|---|---|
2 | -1 | 3 | -1 |
1 | -1 | 2 | 1 |
0 | 1 | 1 | 0 |
graph <- 위의 토마토 창고
ripes <- 익은 토마토들 위치
queue <- BFS용 큐
for ripe in ripes : queue.append(ripe) # 익은 토마토들 위치 초기값으로 넣음
while queue:
x, y = queue.popleft()
for new_x, new_y in ... <- 상하좌우 이동한 위치
if graph[new_x][new_y] == 0:
graph[new_x][new_y] = graph[x][y] + 1 # visited + distance
queue.append((new_x, new_y))
if 0 in graph : return -1
else : return max(graph)
from collections import deque
import sys
class Graph:
def __init__(self, w:int, h:int):
self.w = w
self.h = h
self.graph = []
self.queue = deque()
self.cnt_tomato = 0
for _ in range(h):
inp = list(map(int, sys.stdin.readline().split()))
for i, v in enumerate(inp):
if v == 1 : self.queue.append((_, i))
if v == 0 : self.cnt_tomato += 1
self.graph.append(inp)
def BFS(self):
if len(self.queue) == 0 : return -1
result = 0
while self.queue:
x, y = self.queue.popleft()
k1 = [1, 0, -1, 0]
k2 = [0, 1, 0, -1]
for i in range(4):
new_x = x + k1[i]
new_y = y + k2[i]
if 0<=new_x<self.h and 0<=new_y<self.w and self.graph[new_x][new_y] == 0:
self.graph[new_x][new_y] = self.graph[x][y] + 1
result = max(self.graph[x][y] + 1, result)
self.cnt_tomato -= 1
self.queue.append((new_x, new_y))
if self.cnt_tomato != 0: return -1
else: return result
W, H = map(int, sys.stdin.readline().split())
graph = Graph(W, H)
answer = graph.BFS()
print(answer)