https://www.acmicpc.net/problem/2573
def init():
import sys
ipt = sys.stdin.readline
n, m = map(int, ipt().split())
board = [list(map(int, ipt().split())) for _ in range(n)]
dy = [1,-1,0,0]
dx = [0,0,1,-1]
return n, m, board, 0, 0, dy, dx
def bfs(start):
from collections import deque
q = deque([start])
sy, sx = start
visited[sy][sx] = True
while q:
cy, cx = q.popleft()
for d in range(4):
ny = cy + dy[d]
nx = cx + dx[d]
if not visited[ny][nx] and board[ny][nx] > 0:
visited[ny][nx] = True
q.append((ny, nx))
if board[ny][nx] <= 0:
sea[cy][cx] += 1
def decrease():
for y in range(n):
for x in range(m):
board[y][x] -= sea[y][x]
n, m, board, num, year, dy, dx = init()
while True:
visited = [[False] * m for _ in range(n)]
sea = [[0] * m for _ in range(n)]
num = 0
for y in range(1, n-1):
for x in range(1, m-1):
if board[y][x] > 0 and not visited[y][x]:
num += 1
if num >= 2:
break
bfs((y, x))
decrease()
if num >= 2:
break
if num != 1:
break
year += 1
if num:
print(year)
else:
print(0)