We need to solve: given a grid n x m (<=1000 each, so up to 1e6 cells). For each obstacle cell '*', treat it as empty (only that one cell changes) and compute the size of the connected component (by 4-direction adjacency) that would contain that cell, after making that cell empty. All other cells remain as they are (including other obstacles). We output for empty cells '.' and for obstacles the computed size modulo 10 (so only one digit). Compute efficiently.
Brute force: For each '', temporarily set it to '.' and run BFS/DFS to get component size. That would be O(k * nm) where k is number of obstacles, worst case O((n*m)^2) ~ 1e12 not feasible.
We need to precompute something.
Observation: The connected component if we convert a single '*' to '.' is essentially the union of the sizes of the adjacent connected components of empty cells (4-neighbors) plus 1 (the cell itself). However, careful: The adjacent empty cells may belong to the same component if they are connected through other paths not via the obstacle cell. So we need the total size of the distinct connected components among the four neighboring empty cells, plus 1. And modulo 10 for output.
Thus for each obstacle cell, we can compute answer = (1 + sum_{unique neighboring components sizes}) mod 10.
We need to pre-label each empty cell with its component ID and size. Standard BFS/DFS flood fill.
Then for each '*', look at its up, down, left, right neighbors that are empty. Collect their component IDs, compute sum of sizes of distinct IDs, add 1, mod 10.
Edge cases: if no neighboring empty cells, answer = 1 mod 10 => 1.
We must output for empty cells '.'.
Complexities: O(nm) for BFS, O(nm) for output (scanning each cell and computing answer for obstacles). That's fine.
But note: n,m <= 1000 => 1e6 cells; BFS/DFS with recursion might stack overflow; better use iterative BFS queue or iterative DFS with stack. Python: use deque BFS.
We'll implement in Python? The problem statement talks about C++, Java but we can use Python with fast I/O. But n,m up to 1000, total cells 1e6; Python BFS might be borderline but likely okay with optimized code. However, the output format requires printing a matrix of characters, we can build a list of strings and print. The BFS/DFS in Python might be a bit slow due to loops, but should pass within typical time limits? Usually 1e6 BFS operations is okay in Python if careful. But we need to be mindful of recursion depth (use iterative). Use collections.deque.
Alternative: Use union-find (disjoint set) to compute component sizes for empty cells. Actually we can also use DFS labeling.
We need to assign each empty cell a component ID. Steps:
-
Create a grid array of characters (list of strings or list of lists). We'll need to modify? We can keep as list of strings but we need to label each empty cell with an ID. We'll create a separate 2D array comp_id of size n x m, initialize to -1 for obstacles.
-
Iterate through all cells. If cell is '.' and comp_id not assigned, BFS to fill that component, assign a new ID, and compute size. Store size in an array comp_size (list). For each cell visited, set comp_id[i][j] = id.
After this, we have mapping.
Then for each obstacle cell, compute:
- Initialize set() to store distinct comp_ids from neighbors. But using Python set for each obstacle might be overhead if many obstacles (up to 1e6). However total obstacles up to 1e6, we must process each. Using set per obstacle would be heavy. But we can avoid set because at most 4 neighbors, we can just check manually if ids are distinct; we can do something like:
ids = []
for each neighbor:
if neighbor is within bounds and comp_id[ni][nj] != -1:
cid = comp_id[ni][nj]
if cid not in ids: # can check with small list
ids.append(cid)
Then sum = sum(comp_size[cid] for cid in ids)
ans = (sum + 1) % 10
Because at most 4, using a small list with linear search is fine. That avoids set creation overhead.
Alternatively, we can pre-allocate arrays and use integer flags: Since we only need distinct per obstacle, but IDs can be up to number of components (could be up to ~n*m). Using an array of booleans visited component ID for each obstacle would be expensive if we allocate a fresh array per obstacle. So the small list approach is best.
But we need to be careful: for each obstacle we are scanning neighbors; we need comp_id for neighbors. That's O(4) per obstacle.
So overall O(n*m). Good.
Now implement:
Reading input: use sys.stdin.read() or sys.stdin.buffer. We'll parse quickly.
Plan:
- import sys
- data = sys.stdin.buffer.read().split()
- The first two tokens: n, m = int(data[0]), int(data[1])
- Then next n strings: for i in range(n): row = data[2+i].decode()? Actually .split() splits by whitespace, lines may contain '.' and '*' but no spaces, so each line is a token. But .split() returns bytes if using buffer. We can decode each to ascii string or we can keep as bytes and treat each character. Simpler: data = sys.stdin.buffer.read().split() gives list of bytes. So n = int(data[0]); m = int(data[1]); then rows = [data[i].decode() for i in range(2, 2+n)]. But we need to ensure we have correct length: each row may be of length m. It's fine.
Alternatively, use sys.stdin.readline() in a loop; that's also fast enough for 1e6 chars. We'll use sys.stdin.buffer.readline().
Let's implement with readlines:
import sys
n, m = map(int, sys.stdin.buffer.readline().split())
grid = [sys.stdin.buffer.readline().rstrip(b'\n') for _ in range(n)]
But careful: readline returns bytes, and rstrip removes newline. It will keep as bytes. Each row length should be m. We can keep as bytes string (since characters are ascii). Then we can index grid[i][j] to get byte (int). But for comparisons we need to check if it's ord('.')? Better to decode to string? It's okay.
We'll keep as list of byte strings. But when building output strings, we need to output characters. We'll construct list of char lists then join.
Alternative: Convert grid to list of list of chars? Might use more memory but fine.
We'll process BFS. We need comp_id: a 2D list of ints, initialized with -1. We can create using list comprehension: comp_id = [[-1]*m for _ in range(n)].
Also we need comp_sizes list.
Then flood fill:
id_counter = 0
for i in range(n):
for j in range(m):
if grid[i][j] == ord('.') if using bytes else '.' and comp_id[i][j] == -1:
# BFS
queue = collections.deque()
queue.append((i,j))
comp_id[i][j] = id_counter
size = 0
while queue:
x,y = queue.popleft()
size += 1
# neighbors: up, down, left, right
for dx,dy in [(1,0),(-1,0),(0,1),(0,-1)]:
nx, ny = x+dx, y+dy
if 0 <= nx < n and 0 <= ny < m and grid[nx][ny] == ord('.') and comp_id[nx][ny] == -1:
comp_id[nx][ny] = id_counter
queue.append((nx,ny))
comp_sizes.append(size)
id_counter += 1
But note: grid[i][j] is a byte string row; indexing row[j] returns an integer (byte). In Python, bytes are sequence of ints. So we need to compare to ord('.'). So we can check grid[i][j] == 46 (since '.' ASCII 46) or b'.'[0]. So define DOT = ord('.'). We'll store as integer.
Alternatively, we could decode to string and use '.', but then indexing yields a one-character string, which is slower? Might be okay. But I'll keep as bytes.
Now after labeling, build output.
Initialize a list of list of characters (or list of strings) for output. We'll create an empty 2D list of chars of size n x m, initially all placeholders.
For each cell:
if grid[i][j] == DOT: output[i][j] = '.'
else: # obstacle
# compute sum distinct neighbor component sizes
comps = [] # list of ids
for dx,dy in [(1,0),(-1,0),(0,1),(0,-1)]:
nx, ny = i+dx, j+dy
if 0 <= nx < n and 0 <= ny < m and comp_id[nx][ny] != -1:
cid = comp_id[nx][ny]
# check if not already in comps
if cid not in comps:
comps.append(cid)
total = 1 + sum(comp_sizes[cid] for cid in comps)
digit = total % 10
output[i][j] = str(digit) # single character
After loop, we need to produce output as n lines, each a string of length m. We can do: for i in range(n): print(''.join(output[i]))
But we need to be careful: output[i][j] are strings. We'll use list of lists of characters, then join.
However, building output as list of char lists might use memory but it's fine.
Alternative: We can directly build rows as list of characters and print line by line while computing. But we need comp_sizes and comp_id accessible.
Better: for each i, we can create a list row_out = [] and for j in range(m): compute as above and append char, then after j loop, print(''.join(row_out)). This avoids storing entire output matrix, but we need comp_id for all cells. That's fine; we can compute on the fly. But then we are scanning through grid and comp_id again. We'll do that.
Implementation:
for i in range(n):
row_out = []
for j in range(m):
if grid[i][j] == DOT:
row_out.append('.')
else:
comps = []
# check up (i-1,j)
if i>0 and comp_id[i-1][j] != -1:
cid = comp_id[i-1][j]
if cid not in comps:
comps.append(cid)
# down
if i+1<n and comp_id[i+1][j] != -1:
cid = comp_id[i+1][j]
if cid not in comps:
comps.append(cid)
# left
if j>0 and comp_id[i][j-1] != -1:
cid = comp_id[i][j-1]
if cid not in comps:
comps.append(cid)
# right
if j+1<m and comp_id[i][j+1] != -1:
cid = comp_id[i][j+1]
if cid not in comps:
comps.append(cid)
total = 1
for cid in comps:
total += comp_sizes[cid]
row_out.append(str(total % 10))
print(''.join(row_out))
But careful: The grid may be large; we are doing if cid not in comps (list max 4). That's fine.
Potential optimization: We can precompute the sizes and maybe avoid repeated checks for each neighbor by using a set? Not needed.
Edge Cases: The component sizes could be large, sum up to n*m which is up to 1e6, but modulo 10 only final digit needed. But we compute sum and then mod 10; sum can be up to 1e6, no overflow.
But we need to ensure that for obstacles that are adjacent to same component from multiple sides, we don't double count. That's why we check distinct IDs.
Now confirm examples.
Example1:
3x3
.
.*.
.
Let's compute: Components: The empty cells are corners? Actually corners are '*'? Wait grid:
row0: * . *
row1: . * .
row2: * . *
So empty cells are (0,1), (1,0), (1,2), (2,1). They are all isolated? Actually (0,1) adjacent to (1,1) but (1,1) is '*', so isolated. Similarly others isolated. So each empty cell is component size 1. For obstacle at (0,0): neighbors: down (1,0) size1; right (0,1) size1. They are distinct? (1,0) and (0,1) are different components (both size1). So sum = 1+1+1 =3 => 3. For (1,1) central: neighbors all four: (0,1), (1,0), (1,2), (2,1) each size1 distinct => sum = 1+1+1+1+1=5 => 5. So output matches.
Example2:
4 5
..
..**
...
..*
We can test after coding.
Now complexity: BFS: O(nm). For each empty cell we process it exactly once. BFS uses deque. For each cell we loop over 4 neighbors; total neighbor checks O(4n*m). So fine.
Memory: comp_id: n x m ints, each int maybe 28 bytes? That's ~28 MB for 1e6, maybe high but okay in Python? Actually int objects are large; using list of lists of ints may be memory heavy (each int object ~28 bytes, plus list overhead). For 1e6 cells, that could be ~30 MB for the ints plus overhead of lists (each row list has m references). Might be borderline but typical memory limits are 256 MB, should be okay. However we can try to reduce memory by using array module or using a flat list. But not necessary. But note that we also have grid as list of bytes; that's okay. comp_id could be a list of lists of ints; ints for component ID up to maybe 1e6, but Python ints are big.
Alternatively, we can store comp_id as a 2D array of ints using list of arrays from array module (typecode 'i' for 4-byte ints) or use a flat list. But implementing with a flat list might be simpler and more memory efficient. Let's consider: total cells N = nm. We can map (i,j) to idx = im + j. Then we have comp_id = [-1] * N, grid_flat = something. But we need to quickly access neighbors via flat index. That's doable. However we also need to BFS; we can use flat indices.
But implementing with flat indices may be slightly more complicated but can save memory. However typical Python solutions for 1e6 cells with BFS and 2D list of ints often pass. But it's worth optimizing memory.
Let's estimate: n=m=1000 => 1e6 cells. comp_id as list of lists: each row is a list of m ints. Each int is object (28 bytes). Each row list overhead (like 8 bytes for list object plus 8*m bytes for references? Actually list stores pointers to objects, so each entry is a pointer (8 bytes) plus the int objects separately. So total for comp_id: For each cell, we have an int object (28 bytes) and a pointer in the row list (8 bytes) = 36 bytes per cell, plus row list overhead. So 36 MB for 1e6 => 36 MB. Plus grid: list of n byte strings; each byte string is length m, each byte string uses about m bytes plus overhead. So about 1 MB for grid. Plus BFS queue overhead (stores tuples). BFS might also use a visited flag, but comp_id already serves. So total maybe ~40-50 MB, acceptable.
But some judges have memory limit 256 MB, so fine.
Nevertheless, we might want to use array of ints to be safe. But we'll implement with 2D list for simplicity.
But note: For BFS, we need to store coordinates. We can store them as (i,j) tuples. That's okay but might cause overhead. Could store as single index and decode. But we can also use collections.deque of (i,j) and popleft. That's fine.
We need to be careful about recursion depth if we used DFS; but BFS is iterative.
Now code steps:
- Read n,m.
- Read grid as list of byte strings.
- Convert DOT = ord('.').
- Initialize comp_id = [[-1]*m for _ in range(n)].
- comp_sizes = [].
- Loop over all cells i,j:
if grid[i][j] == DOT and comp_id[i][j] == -1:
BFS: queue = deque(); queue.append((i,j)); comp_id[i][j] = len(comp_sizes) # current id
size = 0
while queue:
x,y = queue.popleft()
size += 1
# four neighbors
if x > 0 and grid[x-1][y] == DOT and comp_id[x-1][y] == -1:
comp_id[x-1][y] = comp_id[i][j] # Actually careful: the id is current id which is len(comp_sizes) before appending? We can store id = len(comp_sizes) before BFS or after? Let's do:
# When we start BFS, we haven't appended the size yet. So we can assign id = len(comp_sizes) (which will be the index after we append later). But then when we assign comp_id for visited cells, we need to use that id. So better:
# id = len(comp_sizes) # current index before appending
# Then after BFS we comp_sizes.append(size)
# But inside BFS we need to know the id; we can store it before loop.
Actually we can do:
cur_id = len(comp_sizes) # since we will add after BFS
comp_id[i][j] = cur_id
size = 0
while queue: ...
comp_sizes.append(size)
Note: When we find neighbor and assign comp_id, we set comp_id[neighbor] = cur_id.
But careful: While BFS we may discover the same cell from different neighbors, but we check visited via comp_id == -1.
Implementation:
from collections import deque
cur_id = len(comp_sizes)
comp_id[i][j] = cur_id
queue.append((i,j))
size = 0
while queue:
x,y = queue.popleft()
size += 1
for dx,dy in dirs:
nx, ny = x+dx, y+dy
if 0 <= nx < n and 0 <= ny < m and grid[nx][ny] == DOT and comp_id[nx][ny] == -1:
comp_id[nx][ny] = cur_id
queue.append((nx,ny))
comp_sizes.append(size)
Yes.
Now for output:
We iterate each cell and compute answer.
Edge Cases: Might have large component sizes, but mod 10.
Testing with examples.
But wait: The output for empty cells is just '.' not component size. So we output '.' for original '.'.
Now confirm for obstacle that is adjacent to empty cells that belong to same component: The sum of distinct component sizes will handle it, as we only add that component's size once.
Now implement.
Potential Pitfalls:
- The grid reading: using sys.stdin.buffer.readline() returns bytes including newline. We'll rstrip(b'\n') but maybe also there are carriage returns? Use .strip()? Better to rstrip(b'\n\r') but not necessary. We'll do row = sys.stdin.buffer.readline().strip() because .strip() removes whitespace including newline, but could also remove spaces? There are no spaces in the row. So safe. But careful: if a row contains only '.' and '', .strip() will not remove '.' or '' because they are not whitespace. So we can use .strip() to remove newline and any trailing spaces. However if there is trailing spaces? Input spec says each line contains m symbols, so no spaces. So .strip() is okay.
But using .strip() also removes leading/trailing whitespace. It won't affect the content. So we can do row = sys.stdin.buffer.readline().strip().
But better to use rstrip(b'\n') to be precise.
We'll use .rstrip(b'\n') to avoid accidentally removing leading/trailing dots? Dots are not newline.
So: row = sys.stdin.buffer.readline().rstrip(b'\n'). This returns bytes of length m (assuming no carriage return). On Windows, lines might end with \r\n, so using .rstrip(b'\n') will not remove \r. Better to use .rstrip() which removes trailing whitespace? Actually .rstrip() removes any trailing whitespace characters including space, tab, newline, carriage return. But it would also remove trailing spaces if any (there are none). So .rstrip() is safer: row = sys.stdin.buffer.readline().rstrip().
But .rstrip() without arguments strips whitespace (including \r\n). That's fine. However it could also strip trailing spaces if they were present (they aren't). So I'll use .rstrip().
Now code.
Let's test with examples manually.
Example1:
Input lines:
"3 3\n"
".\n"
"..\n"
".*\n"
After reading: n=3,m=3. Row0 = b'.' after rstrip. Row1=b'.*.' etc.
Check DOT = ord('.').
BFS: all empty cells are isolated. So comp_id for each '.' gets its own id.
Now output: For (0,0): neighbors: (1,0) and (0,1). Both '.'; comp sizes 1 each; distinct => sum=2+1=3 -> '3'. etc.
Works.
Example2: I'll run mental.
Now one more test: n=1,m=1, cell '*'. No neighbors. Answer = 1%10 = 1. Output "1".
If cell '.', output '.'.
Works.
Now complexity: BFS scanning all cells, each cell processed once; neighbor checks 4 per cell => ~4e6 operations, fine.
But one nuance: In BFS we do 'if grid[nx][ny] == DOT', but grid is a list of byte strings; indexing a bytes string returns an integer (0-255). So comparison with DOT (46) is fine. However for reading we might have newline removed; so indexing works.
Now implement.
But we also need to consider memory for comp_sizes: list of ints up to number of components. That's fine.
Now output: we print each line. Use sys.stdout.write to accumulate? But printing line by line with print might be okay. However for large output (1e6 characters), printing with print each line is fine.
But we can accumulate in a list of strings and then join with newline and write once to stdout for speed. Let's do:
out_lines = []
for i in range(n):
row_out = []
for j in range(m):
if grid[i][j] == DOT:
row_out.append('.')
else:
comps = []
if i > 0 and comp_id[i-1][j] != -1:
cid = comp_id[i-1][j]
if cid not in comps:
comps.append(cid)
if i+1 < n and comp_id[i+1][j] != -1:
cid = comp_id[i+1][j]
if cid not in comps:
comps.append(cid)
if j > 0 and comp_id[i][j-1] != -1:
cid = comp_id[i][j-1]
if cid not in comps:
comps.append(cid)
if j+1 < m and comp_id[i][j+1] != -1:
cid = comp_id[i][j+1]
if cid not in comps:
comps.append(cid)
total = 1
for cid in comps:
total += comp_sizes[cid]
row_out.append(str(total % 10))
out_lines.append(''.join(row_out))
sys.stdout.write('\n'.join(out_lines))
But note: In Python, str(total % 10) gives a digit char. Good.
But we need to ensure we import sys.
Now about reading: We need to ensure we use sys.stdin.buffer for reading.
Potential issue: If we read using .readline().rstrip(), we get bytes; but then later we compare grid[i][j] == DOT. However, in the output we need to check if the cell is empty to output '.'; but we also have comp_id array. However, for obstacles we compute answer. But for empty cells, we always output '.' regardless of component. So we can just check grid[i][j] == DOT to decide. So fine.
Now we can finalize code.
But I recall that there might be a nuance: In the BFS, we use grid for checking if neighbor is empty. However, during BFS we also need to check visited via comp_id. That's correct.
Now performance: The BFS loops use Python loops; but it should be okay.
But we need to be careful about using list of lists for comp_id. Each access comp_id[i][j] is double indexing which is a bit slower. But acceptable.
Now test with example2 quickly manually? Let's code in mind:
Input:
4 5
..
..**
...
..*
I'll compute component labeling manually.
Row0: ".."
Indices: (0,0)='', (0,1)='', (0,2)='.', (0,3)='.', (0,4)=''
Row1: ".."
(1,0)='.', (1,1)='.', (1,2)='', (1,3)='', (1,4)=''
Row2: "..."
(2,0)='.', (2,1)='', (2,2)='.', (2,3)='', (2,4)='.'
Row3: ".."
(3,0)='', (3,1)='.', (3,2)='', (3,3)='.', (3,4)=''
Now empty cells components:
Let's find connected components.
Start from (0,2): neighbors: up none, down (1,2) is '', left (0,1) '', right (0,3) '.'; so (0,2) connected to (0,3). (0,3) neighbors: down (1,3) '', left (0,2) already, right (0,4) ''. So component A: cells {(0,2),(0,3)} size 2.
(1,0): neighbors: right (1,1) '.'; down (2,0) '.'; up (0,0) '', left none. (1,0) connects to (1,1) and (2,0). (1,1) neighbors: right (1,2) '', down (2,1) '', left (1,0). So (1,1) part of same component. (2,0) neighbors: up (1,0), right (2,1) '', down (3,0) '*'. So (2,0) part of same. Also (2,0) might connect to something else? Not. So component B: {(1,0),(1,1),(2,0)} size 3.
(2,2): neighbors: up (1,2) '', down (3,2) '', left (2,1) '', right (2,3) ''. isolated? Actually all four are obstacles. So (2,2) alone, component C size 1.
(2,4): neighbors: up (1,4) '', down (3,4) '', left (2,3) '*', right none. So isolated, component D size 1.
(3,1): neighbors: up (2,1) '', down none, left (3,0) '', right (3,2) ''. Actually left (3,0) is '', right (3,2) '', up (2,1) ''. So isolated? Wait (3,1) is '.'? Row3: "..": index1 is '.'? Actually row3: positions: 0:'',1:'.',2:'',3:'.',4:''. So (3,1) is '.'; neighbors: (2,1) is '' (row2 index1), (3,0) '', (3,2) '*', (4,1) out. So indeed isolated, component E size 1.
(3,3): '.'; neighbors: up (2,3) '', left (3,2) '', right (3,4) '*', down none. So isolated, component F size 1.
Also (maybe (1,?) no other empty cells: (1,0),(1,1) done; (0,2),(0,3) done; (2,0) done; (2,2) done; (2,4) done; (3,1) done; (3,3) done. So components and sizes: A:2, B:3, C:1, D:1, E:1, F:1.
Now compute obstacles:
Let's produce output matrix as per example:
Output given:
46..3
..732
.6.4.
5.4.3
Let's test our method:
We'll compute for each '*' cell the answer.
Coordinates (0,0): ''. Neighbors: down (1,0) component B size3; right (0,1) ''? Actually right (0,1) is '*', not empty. So only down. Also up/left none. So sum = size3 = 3; +1 = 4. mod10 = 4. Output[0][0] = '4'. In given output, first cell is '4'? Output line0: "46..3" => first char '4'. Good.
(0,1): ''. Neighbors: left (0,0) ''; right (0,2) component A size2; down (1,1) component B size3. So distinct: A and B sizes 2 and 3 => sum=2+3=5; +1=6 => mod10=6. Given output line0 second char is '6'? Actually "46..3" => second char '6'. Yes.
(0,4): ''. Neighbors: left (0,3) component A size2; down (1,4) ''? Actually (1,4) is '*'; up none; right none. So only left => size2; +1=3 => '3'. Output line0 last char is '3', matches.
(1,2): ''. Neighbors: up (0,2) component A size2; left (1,1) component B size3; right (1,3) ''? (1,3) is '*'; down (2,2) component C size1. So distinct: A(2), B(3), C(1) => sum=2+3+1=6; +1=7 => '7'. Output line1 third char? Row1: "..732" => characters: index0 '.', index1 '.', index2 '7', index3 '3', index4 '2'. So (1,2) is index2 => '7', matches.
(1,3): ''. Neighbors: left (1,2) ''; right (1,4) ''; up (0,3) component A size2; down (2,3) ''. So only up => size2; +1=3 => '3'. Output line1 index3 is '3', matches.
(1,4): ''. Neighbors: left (1,3) ''; up (0,4) '*'; down (2,4) component D size1; right none. So only down => size1; +1=2 => '2'. Output line1 index4 is '2', matches.
(2,1): '*'. Neighbors: up (1,1) component B size3; left (2,0) component B? Actually (2,0) is part of B as well, so same component B; right (2,2) component C size1; down (3,1) component E size1. Distinct: B(3), C(1), E(1) => sum=3+1+1=5; +1=6 => '6'. Output line2: ".6.4." index1 is '6', matches.
(2,3): ''. Neighbors: up (1,3) ''; left (2,2) component C size1; right (2,4) component D size1; down (3,3) component F size1. Distinct: C(1), D(1), F(1) => sum=1+1+1=3; +1=4 => '4'. Output line2 index3 is '4', matches.
(3,0): '*'. Neighbors: up (2,0) component B size3; right (3,1) component E size1; down none; left none. Distinct: B(3), E(1) => sum=4; +1=5 => '5'. Output line3 index0 is '5', matches.
(3,2): '*'. Neighbors: up (2,2) component C size1; left (3,1) component E size1; right (3,3) component F size1; down none. Distinct: C(1), E(1), F(1) => sum=3; +1=4 => '4'. Output line3 index2 is '4', matches.
(3,4): '*'. Neighbors: left (3,3) component F size1; up (2,4) component D size1; distinct: F(1), D(1) => sum=2; +1=3 => '3'. Output line3 index4 is '3', matches.
Also empty cells output '.'; that matches output lines: row0: "46..3" => positions (0,2) and (0,3) are '.'; row1: "..732" => (1,0) and (1,1) '.'; row2: ".6.4." => (2,0), (2,2), (2,4) '.'; row3: "5.4.3" => (3,1) and (3,3) '.'.
All correct.
Thus algorithm works.
Now edge cases: What if component sizes are huge? Summing them is fine, mod10.
Now, we need to output digits only, not numbers with more than one digit. Since modulo 10 yields a single digit.
Now time to implement.
But note: There is also a nuance: When we compute sum of component sizes, the component sizes are based on the original grid. When we convert an obstacle to empty, the component that forms is the union of adjacent components plus the cell. But the component sizes we use (precomputed) are the sizes of each component as they exist originally. However, if we convert a cell to empty, does it merge components? Yes, it merges the adjacent components. The size after merging is exactly 1 + sum of sizes of those adjacent components. However, note that if those components are already connected via other paths (not through this cell), they would already be the same component. But they are distinct components because otherwise they'd have the same ID. So correct.
Thus answer = (1 + sum distinct neighbor component sizes) % 10.
Now implement.
We also might consider using sys.setrecursionlimit but not needed.
Now coding.
One more optimization: For reading the grid, we may want to store as a flat list of bytes or as a list of strings to speed up indexing? Currently using grid[i][j] for each access. In BFS, we do many neighbor checks. Might be okay. But we could convert grid into a list of bytearray to make indexing faster and mutable? Not necessary.
But for BFS we can also convert the grid to a flat list of integers (0 for empty, 1 for obstacle) to speed up? We'll keep as bytes.
But we need to be careful: When we do grid[i][j], that's indexing into a bytes object. That's fast.
Now, we need to consider that BFS will use a lot of memory if we use deque and store tuples. Each tuple (int,int) takes some memory. But total BFS visits each cell once, so maximum number of tuples in deque is O(width of BFS). But the maximum simultaneous size could be up to nm in worst case if the component is large and we use BFS with many elements. However, using deque, the memory for the queue could be large. But still up to 1e6 tuples (each tuple two ints) could be heavy (maybe ~56 bytes per tuple?), leading to high memory (50+ MB). But we can optimize BFS by using a custom queue: we can use collections.deque of single integers (flat index) to reduce overhead. But it's not necessary? Might be borderline memory but let's estimate: If BFS processes a large component, the queue may hold many cells at the frontier. In a grid BFS, the maximum queue size is about O(min(n,m))? Actually for a BFS on a grid, the queue can get large; for a component that is like a big area, the frontier at a certain layer can be up to O(n) or O(m). For a 1000x1000, the maximum frontier could be 1000? Actually if you have a full grid of empty cells, BFS from one corner: queue size can be as large as the perimeter of the visited region. At its maximum, it could be ~2000? That's not too high. Actually BFS on grid: Starting from a point, the frontier is roughly the boundary of the visited area. The maximum queue size for BFS on a grid of N cells is O(sqrt(N))? For a 2D grid, BFS that expands uniformly, the number of nodes in the queue at any time is about the perimeter of the visited area, which is O(sqrt(N)) for a roughly circular shape. For a 1000x1000 grid, sqrt(N)=1000. But if the shape is long and narrow, it could be larger: consider a component that is a single row of 1000 cells. BFS from leftmost: queue would at some point hold all cells? Let's simulate: start with leftmost cell; pop it, push its right neighbor. The queue would then have one cell. Actually typical BFS: while queue: pop, push neighbors. For a linear chain, the queue size stays 1 (if we process sequentially). Actually if you have a path, BFS will expand one step at a time, but because you pop one and push maybe 1 or 2 (but due to visited checks, each neighbor not visited). For a line of 1000 cells, BFS from one end: initially queue=[pos0]. Pop, push neighbor (pos1) => queue=[pos1]. Then pop, push neighbor (pos2) => queue=[pos2]. So queue size stays 1. So maximum queue size is limited. For a shape with many branches, it can be larger. But worst-case in grid BFS with 4-connectivity, maximum queue size can be O(N) in a "comb" shape? Actually think of a star shape: starting from a center, all four neighbors are added, then each neighbor may add more. But still, the frontier can be up to O(N) if the component is like a "thin" region that branches? For example, consider a full grid: BFS from a corner: at step k, the frontier consists of cells with Manhattan distance = k. The number of such cells is roughly 4k, but bounded by the grid size. The maximum frontier occurs at around middle, maybe about 2min(n,m) ? For 1000x1000, max distance from corner is 1998, but number of cells at distance d is roughly min(d+1, 2*1000 - d -1) * something? Actually in a rectangle, the number of cells with Manhattan distance d from a corner is something like for d up to min(n,m)-1 it's d+1, then constant, then decreasing. The maximum is min(n,m) which is 1000. So frontier up to 1000. So queue size likely <=1000. So memory is fine.
Thus using deque of tuples is okay.
But for each BFS we allocate new deque. However we might want to reuse a deque? Not necessary.
Now potential improvement: Use a list as stack for DFS (iterative) might be faster? Not necessary.
Now consider if there are many obstacles and few empty cells. That's fine.
Now final code.
But we must ensure that we use sys.stdin.buffer and sys.stdout.write for output large.
Now let's write the code.
I'll also add a main guard.
Implementation details:
-
DOT = ord('.')
-
In BFS, for each neighbor we check if grid[nx][ny] == DOT. But we already have comp_id as -1 for obstacles and visited.
-
Use directions = [(1,0), (-1,0), (0,1), (0,-1)].
Now test with examples.
Potential bug: In BFS, we set comp_id[neighbor] = cur_id, but cur_id is defined before BFS as len(comp_sizes). That works because we haven't added the size yet; after BFS we comp_sizes.append(size). So the mapping is correct.
Now for output: For obstacles, we compute sum of comp_sizes[ids]. But what if a neighbor is an empty cell that is part of a component that includes other cells, but the size is stored in comp_sizes. That's fine.
Now edge case: An obstacle may be adjacent to an empty cell that is part of a component that is huge. Sum may be large, but we take mod 10. So fine.
Now verify with a simple case:
n=2,m=2
..
..
All empty. Output should be:
..
..
Because we output '.' for empty cells; obstacles none. So all '.'.
Our code: comp_id for all cells will be assigned to same component? Actually they are all connected? For 2x2 all '.'; all four cells connected. So BFS will label all as one component with size 4. For output, for each cell we check if grid[i][j] == DOT -> output '.'; so correct.
Now case with all obstacles: n=2,m=2:
**
**
Output should be:
11
11
Because each obstacle becomes empty, with no adjacent empty neighbors, so answer =1 mod10 -> 1.
Our code: There are no empty cells, so comp_sizes empty, comp_id all -1. For each obstacle, comps list empty, total = 1, digit = 1. Output '1' for each. Good.
Now case where an obstacle is adjacent to multiple empty cells of same component. Example: grid:
..
.
..
The central cell (1,1) is '', its neighbors are all '.' that are part of the same component? Actually the four corners? Let's see: (0,1) and (1,0) and (1,2) and (2,1) are '.'; But are they all connected? (0,1) connects to (0,0)? Actually (0,0) is '.'? No, the grid: row0: '.' '' '.'? Actually row0: . * .; row1: * . ; row2: . * . So empty cells: (0,0) '.', (0,2) '.', (1,1) is '', (2,0) '.', (2,2) '.'? Wait row2: . * . So (2,0) '.', (2,2) '.'. And also (0,1) '' etc. Actually the only empty cells are at corners? Let's list: row0: col0 '.', col1 '', col2 '.'; row1: col0 '', col1 '.', col2 ''; row2: col0 '.', col1 '', col2 '.'. So empty cells: (0,0), (0,2), (1,1), (2,0), (2,2). Are they connected? (0,0) adjacent down (1,0) '' and right (0,1) '', so isolated. (0,2) similar. (1,1) is isolated? It neighbors are all ''. (2,0) isolated. (2,2) isolated. So each is separate component. So obstacle at (1,0) for example would have neighbors (0,0) and (1,1) and (2,0). Those are three distinct components. So fine.
But consider a case where two neighbors belong to same component because they are connected through other paths not via the obstacle. Example: A shape like:
..*
...
..*
But actually for an obstacle, neighbors could be two cells that are connected around through other empty cells. E.g., grid:
...
..
...
All cells empty except center ''. Then neighbors up,down,left,right are all part of the same component (the outer ring is all connected via edges not through center). Actually with all cells empty except center '', the empty cells form a component that is all 8? Actually 4-connectivity: the cells around center are up, down, left, right; but also the corners are connected to them via other paths. So all empty cells are in one component. So for the obstacle at center, its four neighbors are all same component. Our distinct list will add only once, sum = size of that component (which is nm - 1) plus 1 = n*m. That matches the component size if we fill center.
Our method works.
Now code.
But there is a nuance: The sum of component sizes may exceed 1e9 but Python ints handle.
Now coding.
After coding, test with sample.
Now potential pitfalls: Input may have rows that include spaces? No.
Now time to write final answer.
We'll produce Python solution.
But note: In Python, using .decode() for each row may be slower. We can keep as bytes and compare to ord('.'). That's fine.
Now final code:
import sys
from collections import deque
def main():
data = sys.stdin.buffer
n_m = data.readline().split()
if not n_m:
return
n, m = map(int, n_m)
grid = []
for _ in range(n):
line = data.readline().rstrip()
# ensure line length m; maybe there is trailing newline removed
grid.append(line) # bytes
DOT = ord('.')
comp_id = [[-1]*m for _ in range(n)]
comp_sizes = []
dirs = [(1,0), (-1,0), (0,1), (0,-1)]
for i in range(n):
for j in range(m):
if grid[i][j] == DOT and comp_id[i][j] == -1:
cur_id = len(comp_sizes)
q = deque()
q.append((i,j))
comp_id[i][j] = cur_id
size = 0
while q:
x, y = q.popleft()
size += 1
for dx, dy in dirs:
nx, ny = x+dx, y+dy
if 0 <= nx < n and 0 <= ny < m and grid[nx][ny] == DOT and comp_id[nx][ny] == -1:
comp_id[nx][ny] = cur_id
q.append((nx, ny))
comp_sizes.append(size)
out_lines = []
for i in range(n):
row_out = []
for j in range(m):
if grid[i][j] == DOT:
row_out.append('.')
else:
comps = []
# up
if i > 0 and comp_id[i-1][j] != -1:
cid = comp_id[i-1][j]
if cid not in comps:
comps.append(cid)
# down
if i + 1 < n and comp_id[i+1][j] != -1:
cid = comp_id[i+1][j]
if cid not in comps:
comps.append(cid)
# left
if j > 0 and comp_id[i][j-1] != -1:
cid = comp_id[i][j-1]
if cid not in comps:
comps.append(cid)
# right
if j + 1 < m and comp_id[i][j+1] != -1:
cid = comp_id[i][j+1]
if cid not in comps:
comps.append(cid)
total = 1
for cid in comps:
total += comp_sizes[cid]
row_out.append(str(total % 10))
out_lines.append(''.join(row_out))
sys.stdout.write('\n'.join(out_lines))
if __name__ == '__main__':
main()
That should work.
Now we need to ensure we used .rstrip() on lines, but what if lines contain leading/trailing spaces? Not. So fine.
One more micro-optimization: For neighbor checking, we could use a loop over dirs again. But current explicit up/down/left/right is fine, and might be faster because we avoid creating a small list of directions for each cell. But it's okay.
We could also compute using directions:
for dx,dy in dirs: if bounds and comp_id[nx][ny]!=-1: add distinct. That would be shorter. But I'll keep explicit for readability.
But note: In BFS we used dirs list, which is okay.
Now one more: To avoid if cid not in comps (list) each time, we could just use a set but then need to create a set for each obstacle; but set creation overhead might be larger than small list with up to 4 checks. So list is fine.
Now final answer.
But the problem statement says: "The answer should be printed as a matrix with n rows and m columns. The j-th symbol of the i-th row should be "." if the cell is empty at the start. Otherwise the j-th symbol of the i-th row should contain the only digit —- the answer modulo 10." So we are correct.
Now test with sample:
Input:
3 3
.
.*.
.
Our code: grid rows as bytes. BFS: four empty cells, each isolated. comp_sizes = [1,1,1,1]; ids assigned. For (0,0): neighbors down (1,0) cid? (1,0) empty? Actually row1: "..", bytes: index0 '.', index1 '', index2 '.'; so (1,0) is '.' with some cid, size 1; right (0,1) is '.' with another cid, size1; total = 1+1+1=3 => '3'. So row0: first char '3', second '.'? Wait (0,1) is '.' => output '.'; third char obstacle => compute neighbors left (0,2)? Actually (0,2) is ''? In row0: "." => index0 '', index1 '.', index2 '*'. So (0,2) is obstacle. So row0 output: '3', '.', '3'? But expected output: "3.3" -> that's '3', '.', '3' indeed. However our code for (0,1) is '.' so outputs '.'; good.
Now for row1: ". * ." => (1,0) '.' -> '.'; (1,1) obstacle -> neighbors up (0,1) '.' size1, down (2,1) '.' size1, left (1,0) '.' size1, right (1,2) '.' size1 -> distinct all four? Actually (0,1) and (2,1) and (1,0) and (1,2) are all different components because each empty cell isolated. So total = 1+4=5 => '5'. (1,2) is '.' -> '.'; So row1: ".5." as expected.
Row2: "." => similar to row0 => '3','.','3'. So output lines: "3.3", ".5.", "3.3". matches.
Now second sample: as earlier matched.
Thus correct.
Now consider performance: BFS labeling uses Python loops; for each cell we do neighbor checks. For 1e6 cells, BFS will process each cell once and each neighbor check 4 times, so about 4e6 checks. That's fine.
But we need to ensure that we use fast I/O; using sys.stdin.buffer and sys.stdout.write.
Now final code ready.
But I recall a potential issue: The grid rows read with .rstrip() might remove trailing newline but also might remove trailing spaces if any; but not.
However, if a line contains a carriage return '\r' on Windows, .rstrip() will remove it too because it's whitespace. So fine.
Now we should also consider that input may have extra spaces after the grid lines? Unlikely.
Now final answer.
But note: In the BFS, we used grid[nx][ny] == DOT. grid is list of bytes; indexing returns an integer. That's okay.
However, there is subtle: When we read lines, we used .rstrip() which removes trailing whitespace. But if the line has leading spaces (not possible), it wouldn't remove. So fine.
Now we output as strings. Use sys.stdout.write once, or line by line? I used join. That's fine.
Now we need to ensure that for empty cells, we output '.' not the digit.
All good.
One more thought: The modulo 10 requirement: The answer modulo 10 printed as a single digit. However, if the answer modulo 10 is 0, we should output '0'? Yes, because it says "the only digit — the answer modulo 10". So if sum+1 mod 10 = 0, output '0'. Example: if total size is 10, answer = 0. That's possible. So we must output '0' not skip. That's fine as we do str(total % 10). That yields '0'.
Now final code.
But we might want to include a check for when n=0 or m=0? Not needed.
Now final answer.
Potential improvement: Use array module for comp_id: but not necessary.
Now we produce final solution.
One nuance: In BFS, we set comp_id[neighbor] = cur_id before pushing to queue. This ensures we don't push duplicate. That's fine.
Now I'll craft the final answer with explanation.
But the user asked to "You are given ..." and we need to produce solution. The final answer is the code.
I'll include explanation in the final response? The user expects a solution. So I'll output the code.
Now finalize. ```python
import sys
from collections import deque
def main():
data = sys.stdin.buffer
n_m = data.readline().split()
if not n_m:
return
n, m = map(int, n_m)
grid = []
for _ in range(n):
line = data.readline().rstrip() # remove trailing newline, keeps bytes
grid.append(line) # each row is a bytes object
DOT = ord('.')
comp_id = [[-1] * m for _ in range(n)]
comp_sizes = []
dirs = [(1, 0), (-1, 0), (0, 1), (0, -1)]
# label all connected components of empty cells
for i in range(n):
for j in range(m):
if grid[i][j] == DOT and comp_id[i][j] == -1:
cur_id = len(comp_sizes)
q = deque()
q.append((i, j))
comp_id[i][j] = cur_id
size = 0
while q:
x, y = q.popleft()
size += 1
for dx, dy in dirs:
nx, ny = x + dx, y + dy
if 0 <= nx < n and 0 <= ny < m and grid[nx][ny] == DOT and comp_id[nx][ny] == -1:
comp_id[nx][ny] = cur_id
q.append((nx, ny))
comp_sizes.append(size)
out_lines = []
for i in range(n):
row_out = []
for j in range(m):
if grid[i][j] == DOT:
row_out.append('.')
else:
# collect ids of distinct neighbouring components
neigh = []
# up
if i > 0 and comp_id[i-1][j] != -1:
cid = comp_id[i-1][j]
if cid not in neigh:
neigh.append(cid)
# down
if i + 1 < n and comp_id[i+1][j] != -1:
cid = comp_id[i+1][j]
if cid not in neigh:
neigh.append(cid)
# left
if j > 0 and comp_id[i][j-1] != -1:
cid = comp_id[i][j-1]
if cid not in neigh:
neigh.append(cid)
# right
if j + 1 < m and comp_id[i][j+1] != -1:
cid = comp_id[i][j+1]
if cid not in neigh:
neigh.append(cid)
total = 1
for cid in neigh:
total += comp_sizes[cid]
row_out.append(str(total % 10))
out_lines.append(''.join(row_out))
sys.stdout.write('\n'.join(out_lines))
if name == 'main':
main()