46 lines
1.1 KiB
Python
46 lines
1.1 KiB
Python
from collections import deque
|
|
|
|
N, M = map(int, input().split())
|
|
paper = []
|
|
cheese = 0
|
|
for i in range(N) :
|
|
paper.append(list(map(int, input().split())))
|
|
for n in paper[i] :
|
|
if n == 1 :
|
|
cheese += 1
|
|
|
|
dx = [1,-1,0,0]
|
|
dy = [0,0,1,-1]
|
|
q = deque()
|
|
time = 0
|
|
|
|
while cheese != 0 :
|
|
visited = [[0]*M for _ in range(N)]
|
|
q.append((0,0))
|
|
visited[0][0] = 1
|
|
|
|
while q :
|
|
cx, cy = q.popleft()
|
|
|
|
for i in range(4) :
|
|
nx, ny = cx + dx[i], cy + dy[i]
|
|
|
|
if 0<=nx<M and 0<=ny<N and paper[ny][nx] == 0 and visited[ny][nx] == 0 :
|
|
q.append((nx, ny))
|
|
visited[ny][nx] = 1
|
|
|
|
for j in range(4) :
|
|
nnx, nny = nx+dx[j], ny+dy[j]
|
|
|
|
if 0<=nnx<M and 0<=nny<N and paper[nny][nnx] == 1 :
|
|
visited[nny][nnx] += 1
|
|
|
|
for i in range(N) :
|
|
for j in range(M) :
|
|
if paper[i][j] == 1 and visited[i][j] >= 2 :
|
|
paper[i][j] = 0
|
|
cheese -= 1
|
|
|
|
time += 1
|
|
|
|
print(time) |