|
| 1 | +import sys |
| 2 | +from collections import deque |
| 3 | + |
| 4 | +read = lambda: sys.stdin.readline().rstrip() |
| 5 | + |
| 6 | + |
| 7 | +class Problem: |
| 8 | + def __init__(self): |
| 9 | + self.n, self.m = map(int, read().split()) |
| 10 | + self.matrix = [list(map(int, list(read()))) for _ in range(self.n)] |
| 11 | + |
| 12 | + def solve(self) -> None: |
| 13 | + for row in self.update_matrix(): |
| 14 | + print(*row, sep="") |
| 15 | + |
| 16 | + def update_matrix(self) -> list[list[int]]: |
| 17 | + for count, walls in self.find_group(): |
| 18 | + for x, y in walls: |
| 19 | + self.matrix[y][x] += count |
| 20 | + self.matrix[y][x] %= 10 |
| 21 | + |
| 22 | + return self.matrix |
| 23 | + |
| 24 | + def find_group(self) -> list[tuple[int, set[tuple[int, int]]]]: |
| 25 | + group, stack, visited = ( |
| 26 | + [], |
| 27 | + deque([(1, {(x, y)}, set()) for x in range(self.m) for y in range(self.n) if self.matrix[y][x] == 0]), |
| 28 | + set(), |
| 29 | + ) |
| 30 | + |
| 31 | + while stack: |
| 32 | + count, paths, walls = stack.pop() |
| 33 | + if len(paths - visited) != len(paths): |
| 34 | + continue |
| 35 | + |
| 36 | + new_path = set() |
| 37 | + for x, y in paths: |
| 38 | + visited.add((x, y)) |
| 39 | + |
| 40 | + for dx, dy in ((0, 1), (0, -1), (1, 0), (-1, 0)): |
| 41 | + nx, ny = x + dx, y + dy |
| 42 | + if (nx, ny) in visited or not (0 <= nx < self.m and 0 <= ny < self.n): |
| 43 | + continue |
| 44 | + |
| 45 | + if self.matrix[ny][nx] == 0: |
| 46 | + new_path.add((nx, ny)) |
| 47 | + else: |
| 48 | + walls.add((nx, ny)) |
| 49 | + |
| 50 | + if new_path: |
| 51 | + stack.append((count + len(new_path), new_path, walls)) |
| 52 | + else: |
| 53 | + group.append((count, walls)) |
| 54 | + |
| 55 | + return group |
| 56 | + |
| 57 | + |
| 58 | +if __name__ == "__main__": |
| 59 | + Problem().solve() |
0 commit comments