πŸ—οΈ Algorithm/🟩 λ°±μ€€

🟩 [λ°±μ€€] [Python] [BFS] 7576번_ν† λ§ˆν† 

Dbswnstjd 2022. 11. 7. 20:39

문제

https://www.acmicpc.net/problem/7576

 

7576번: ν† λ§ˆν† 

첫 μ€„μ—λŠ” μƒμžμ˜ 크기λ₯Ό λ‚˜νƒ€λ‚΄λŠ” 두 μ •μˆ˜ M,N이 주어진닀. M은 μƒμžμ˜ κ°€λ‘œ 칸의 수, N은 μƒμžμ˜ μ„Έλ‘œ 칸의 수λ₯Ό λ‚˜νƒ€λ‚Έλ‹€. 단, 2 ≤ M,N ≤ 1,000 이닀. λ‘˜μ§Έ μ€„λΆ€ν„°λŠ” ν•˜λ‚˜μ˜ μƒμžμ— μ €μž₯된 ν† λ§ˆν† 

www.acmicpc.net

풀이

from collections import deque

m, n = map(int, input().split())
matrix = [list(map(int, input().split())) for _ in range(n)]
queue = deque([])
dx, dy = [-1, 1, 0, 0], [0, 0, -1, 1]
res = 0

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

def bfs():
    while queue:
        x, y = queue.popleft()
        for i in range(4):
            nx, ny = dx[i] + x, dy[i] + y
            if 0 <= nx < n and 0 <= ny < m and matrix[nx][ny] == 0:
                matrix[nx][ny] = matrix[x][y] + 1
                queue.append([nx, ny])
bfs()

for i in matrix:
    for j in i:
        if j == 0:
            print(-1)
            exit(0)
    res = max(res, max(i))
print(res - 1)

BFSλ₯Ό μ΄μš©ν•œ 풀이