To solve this problem, we need to model the spread of '2's converting adjacent '1's in the matrix. This can be efficiently achieved using Breadth-First Search (BFS), as BFS naturally explores neighbors level by level, which corresponds to the time steps in our problem.
Here's a high-level overview of the algorithm:
-
Initialize the Queue: Start by scanning the entire matrix to find all the cells that initially contain '2'. These cells are our starting points, and we'll add them to a queue for BFS traversal. Also, keep track if there are any '1's in the matrix; if there are none, we can immediately output '0'.
-
Perform BFS: Use the queue to perform BFS. For each cell containing '2', we'll check its adjacent cells (up, down, left, right). If an adjacent cell contains '1', we'll convert it to '2', increment the time by 1, and add it to the queue.
-
Record Time Steps: Keep a variable to record the maximum time taken to convert '1's to '2's during the BFS traversal. This time represents the minimum number of seconds required to convert all '1's.
-
Check for Remaining '1's: After the BFS traversal, scan the matrix again to check if any '1's remain. If there are any, it means they couldn't be converted (possibly because they're isolated and not adjacent to any '2's), and we should output '-1'.
-
Output the Result: If all '1's have been converted, output the maximum time recorded during the BFS traversal.
Here's the Python code implementing the above algorithm:
from collections import deque
import sys
import threading
def main():
import sys
sys.setrecursionlimit(1 << 25)
N_and_M = sys.stdin.readline().split()
while len(N_and_M) < 2:
N_and_M.extend(sys.stdin.readline().split())
N, M = map(int, N_and_M)
N = int(N)
M = int(M)
grid = []
has_one = False
queue = deque()
time_grid = [[-1]*M for _ in range(N)]
for i in range(N):
while True:
line = sys.stdin.readline()
if not line.strip():
continue
row = line.strip().split()
while len(row) < M:
row.extend(sys.stdin.readline().strip().split())
grid_row = list(map(int, row))
break
for j in range(M):
if grid_row[j] == 2:
queue.append( (i, j) )
time_grid[i][j] = 0
if grid_row[j] == 1:
has_one = True
grid.append(grid_row)
if not has_one:
print(0)
return
if not queue:
print(-1)
return
max_time = 0
while queue:
i, j = queue.popleft()
current_time = time_grid[i][j]
max_time = max(max_time, current_time)
for dx, dy in [(-1,0),(1,0),(0,-1),(0,1)]:
ni, nj = i + dx, j + dy
if 0<=ni<N and 0<=nj<M and grid[ni][nj]==1:
grid[ni][nj] = 2
time_grid[ni][nj] = current_time + 1
queue.append( (ni, nj) )
for i in range(N):
for j in range(M):
if grid[i][j] == 1:
print(-1)
return
print(max_time)
threading.Thread(target=main).start()
Explanation of the Code:
- Input Reading: We read the dimensions (N, M) and the grid carefully, ensuring that all values are read correctly even if they span multiple lines.
- Initialization: We prepare the BFS queue with all initial positions of '2's and set up a time grid to keep track of when each cell was converted.
- BFS Traversal: We perform BFS, converting adjacent '1's to '2's, updating the time grid, and tracking the maximum time.
- Post-processing: After BFS, we check if any '1's remain.
- Output: If all '1's have been converted, we output the maximum time; otherwise, we output '-1'.
This solution efficiently handles large inputs within the given time constraints by ensuring that each cell is processed only once, resulting in a time complexity of O(N*M).