[못 푼 문제] 백준 7576

장준서·2022년 4월 16일
0

알고리즘 문제

목록 보기
25/29

정말 간단한 문제였지만 그 쉬운 한가지를 생각하지 못했다. 위 같은 경우 최댄 거리를 찾는 문제라 기본적으로 bfs를 사용하고 시작 지점이 둘 이상인 경우 단순히 시작 지점 둘다 큐에 넣어주면 그만인 것이다.

그리고 하나 더 프로그램을 종료싶은 경우 exit(0)를 사용하자.

from collections import deque

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

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

mx = [1, -1, 0 ,0]
my = [0, 0, 1, -1]

queue = deque()

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

maxi = 1
while queue:
    x, y = queue.popleft()
    maxi = max(maxi, graph[x][y])
    for i in range(4):
        nx = x + mx[i]
        ny = y + my[i]

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

zero = False
for i in range(n):
    if 0 in graph[i]:
        print(-1)
        exit(0)

print(maxi-1)


profile
let's get ready to rumble

0개의 댓글