λ¬Έμ
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λ₯Ό μ΄μ©ν νμ΄
'ποΈ Algorithm > π© λ°±μ€' μΉ΄ν κ³ λ¦¬μ λ€λ₯Έ κΈ
π© [λ°±μ€] [Python] 2468λ²_μμ μμ (1) | 2022.11.09 |
---|---|
π© [λ°±μ€] [Python] 2193λ²_μ΄μΉμ (0) | 2022.11.08 |
π© [λ°±μ€] [Python] [BFS] 1926λ²_κ·Έλ¦Ό (0) | 2022.11.07 |
π© [λ°±μ€] [Python] 1002λ²_ν°λ (0) | 2022.11.07 |
π© [λ°±μ€] [Python] 1629λ²_κ³±μ (0) | 2022.11.07 |