69 lines
1.7 KiB
Python
69 lines
1.7 KiB
Python
from collections import deque
|
|
import sys
|
|
input = sys.stdin.readline
|
|
|
|
N, M = map(int, input().split())
|
|
mapp = [input().rstrip() for _ in range(N)]
|
|
res = [[0]*M for _ in range(N)]
|
|
|
|
area_num = [[-1]*M for _ in range(N)]
|
|
area_size = []
|
|
|
|
def BFS(group, x, y) :
|
|
qu = deque()
|
|
qu.append((x, y))
|
|
area_num[y][x] = group
|
|
cnt = 1
|
|
|
|
while qu :
|
|
cx, cy = qu.popleft()
|
|
|
|
for dx, dy in zip([1,-1,0,0], [0,0,1,-1]) :
|
|
nx, ny = cx + dx, cy + dy
|
|
|
|
if 0 <= nx < M and 0 <= ny < N and mapp[ny][nx] != "1" and area_num[ny][nx] == -1 :
|
|
qu.append((nx, ny))
|
|
cnt += 1
|
|
area_num[ny][nx] = group
|
|
|
|
area_size[group] = cnt
|
|
|
|
group_num = 0
|
|
wall = []
|
|
for y in range(N) :
|
|
for x in range(M) :
|
|
if mapp[y][x] == "1" :
|
|
wall.append((x, y))
|
|
elif area_num[y][x] == -1 :
|
|
area_size.append(0)
|
|
BFS(group_num, x, y)
|
|
group_num += 1
|
|
|
|
for x, y in wall :
|
|
cnt = 1
|
|
neighbor = []
|
|
|
|
for dx, dy in zip([1,-1,0,0], [0,0,1,-1]) :
|
|
nx, ny = x + dx, y + dy
|
|
|
|
if 0 <= nx < M and 0 <= ny < N and area_num[ny][nx] != -1 :
|
|
area = area_num[ny][nx]
|
|
|
|
if len(neighbor) == 0 :
|
|
cnt += area_size[area]
|
|
neighbor.append(area)
|
|
else :
|
|
dupli_check = True
|
|
|
|
for n in neighbor :
|
|
if n == area :
|
|
dupli_check = False
|
|
|
|
if dupli_check :
|
|
cnt += area_size[area]
|
|
neighbor.append(area)
|
|
|
|
res[y][x] = cnt % 10
|
|
|
|
for row in res :
|
|
print("".join(map(str, row))) |