from sys import stdin
from collections import deque
input = stdin.readline
M, N = map(int, input().split())
# M ๊ฐ๋ก, N ์ธ๋ก
tomatoes = []
set_tomatoes = set()
day = 0
for _ in range(N):
inputs = list(map(int, input().split()))
set_tomatoes.update(set(inputs))
tomatoes.append(inputs)
# ํ์ฌ ๋ชจ๋ ํ ๋งํ ๊ฐ ์์๋์ง ํ์ธํ๊ธฐ
if len(set_tomatoes) == 1 and set_tomatoes.pop() == 1:
print(0)
exit()
# ์ต์ ํ ๋งํ ๊ฐ ์๋ ๊ฒฝ์ฐ
if 1 not in set_tomatoes:
print(-1)
exit()
queue = deque([])
# ์ต์ ํ ๋งํ ๋ค queue์ ๋ด๊ธฐ
for x in range(N):
for y in range(M):
if tomatoes[x][y] == 1:
queue.append((x, y))
# bfs
def bfs(graph, queue):
# ์ ํ ์ข ์ฐ
directionX = [-1, 1, 0, 0]
directionY = [0, 0, -1, 1]
next = deque([])
while queue:
x, y = queue.popleft()
for i in range(len(directionX)):
nx, ny = x + directionX[i], y + directionY[i]
if 0 <= nx < N and 0 <= ny < M and graph[nx][ny] == 0:
graph[nx][ny] = 1
next.append((nx, ny))
return graph, next
while queue:
tomatoes, queue = bfs(tomatoes, queue)
day += 1
# print(day, queue)
#
# for tomato in tomatoes:
# print(tomato)
print(day - 1)
โ ์ ๋ต ์ฝ๋
from sys import stdin
from collections import deque
input = stdin.readline
M, N = map(int, input().split())
# M ๊ฐ๋ก, N ์ธ๋ก
tomatoes = []
set_tomatoes = set()
day = 0
for _ in range(N):
inputs = list(map(int, input().split()))
set_tomatoes.update(set(inputs))
tomatoes.append(inputs)
# ํ์ฌ ๋ชจ๋ ํ ๋งํ ๊ฐ ์์๋์ง ํ์ธํ๊ธฐ
if len(set_tomatoes) == 1 and set_tomatoes.pop() == 1:
print(0)
exit()
# ์ต์ ํ ๋งํ ๊ฐ ์๋ ๊ฒฝ์ฐ
if 1 not in set_tomatoes:
print(-1)
exit()
queue = deque([])
# ์ต์ ํ ๋งํ ๋ค queue์ ๋ด๊ธฐ
for x in range(N):
for y in range(M):
if tomatoes[x][y] == 1:
queue.append((x, y))
# bfs
def bfs(graph, queue):
# ์ ํ ์ข ์ฐ
directionX = [-1, 1, 0, 0]
directionY = [0, 0, -1, 1]
next = deque([])
while queue:
x, y = queue.popleft()
for i in range(len(directionX)):
nx, ny = x + directionX[i], y + directionY[i]
if 0 <= nx < N and 0 <= ny < M and graph[nx][ny] == 0:
graph[nx][ny] = 1
next.append((nx, ny))
return graph, next
while queue:
tomatoes, queue = bfs(tomatoes, queue)
day += 1
for tomato in tomatoes:
# ์ต์ง ์์ ํ ๋งํ ๊ฐ ์๋์ง ํ์ธ
if 0 in tomato:
print(-1)
exit()
print(day - 1)