토마토

임정우·2023년 1월 22일

코딩테스트

목록 보기
6/10

1인 부분을 찾아서 각 지점을 큐애 넣어서 bfs를 돌린다

from collections import deque

m,n = map(int, input().split())
graph = []
for i in range(n):
    graph.append(list(map(int,input().split(sep=" "))))

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

def tomato():
    queue = deque()
    for i in range(n):
        for j in range(m):
            if graph[i][j] == 1:
                queue.append((i,j))
    while queue:
        x, y = queue.popleft()
        weight = 0
        for i in range(4):
            nx = x + dx[i]
            ny = y + dy[i]        
    
            if nx >= n or ny >= m or nx < 0 or ny < 0:
                continue
            if graph[nx][ny] == -1:
                continue
            if graph[nx][ny] == 0:
                graph[nx][ny] += graph[x][y] + 1
                queue.append((nx,ny))
                weight += 1
                
    return graph[n-1][m-1]

tomato()

max = 0
is_zero = False
for i in range(n):
    for j in range(m):
        if max < graph[i][j]:
            max = graph[i][j]
        if graph[i][j] == 0:
            is_zero = True

if is_zero == True:
    print(-1)
else:
    print(max-1)
profile
경희대학교 소프트웨어융합학과

0개의 댓글