Given a 2D matrix 'A' of size 'M' x 'N' containing only integers 0, 1, and 2.
Each 2 represents a rotten tomato, each 1 represents a fresh tomato, and each 0 represents an empty cell. A rotten tomato at position (i, j) can rot any adjacent fresh tomato at (i-1, j), (i+1, j), (i, j-1), or (i, j+1) in one unit of time.
Find the minimum time required for all fresh tomatoes to become rotten. If it's impossible for all fresh tomatoes to rot, return -1.
Let 'M' = 3, 'N' = 3, and 'A' =
2 1 1
1 1 0
0 1 1
Initially, the rotten tomato is at (0, 0).
After 1 minute, the fresh tomatoes at (0, 1) and (1, 0) become rotten.
The matrix becomes:
2 2 1
2 1 0
0 1 1
After 2 minutes, the tomato at (1, 1) becomes rotten (from (0,1) or (1,0)).
The matrix becomes:
2 2 1
2 2 0
0 1 1
After 3 minutes, the tomatoes at (0, 2) and (2, 1) become rotten.
The matrix becomes:
2 2 2
2 2 0
0 2 1
After 4 minutes, the tomato at (2, 2) becomes rotten.
The matrix becomes:
2 2 2
2 2 0
0 2 2
All fresh tomatoes have become rotten. The minimum time taken is 4.
The first line contains two integers, 'M' and 'N'.
The next 'M' lines contain 'N' integers each, representing the matrix 'A'.
Output Format :
Return the minimum time required for all fresh tomatoes to become rotten. Return -1 if this is not possible.
Note :
You don’t need to print anything. Just implement the given function.
1 <= 'M', 'N' <= 100
0 <= 'A[i][j]' <= 2
Time Limit: 1 sec
3 3
2 1 1
1 1 0
0 1 1
4
Initially, the rotten tomato is at (0, 0).
The matrix is:
2 1 1
1 1 0
0 1 1
At time 1, tomatoes at (0, 1) and (1, 0) become rotten.
The matrix becomes:
2 2 1
2 1 0
0 1 1
At time 2, the tomato at (1, 1) becomes rotten.
The matrix becomes:
2 2 1
2 2 0
0 1 1
At time 3, tomatoes at (0, 2) and (2, 1) become rotten.
The matrix becomes:
2 2 2
2 2 0
0 2 1
At time 4, the tomato at (2, 2) becomes rotten.
The matrix becomes:
2 2 2
2 2 0
0 2 2
All fresh tomatoes are rotten. The minimum time is 4.
3 3
2 1 2
1 0 1
1 1 1
-1
Consider this problem as finding the shortest path in a grid, where rotten tomatoes spread outwards level by level.
Approach:
Algorithm:
O(M * N), where 'M' is the number of rows and 'N' is the number of columns in the matrix 'A'.
In the worst case, we visit each cell of the matrix at most a constant number of times (when adding to the queue and processing). Thus, the overall time complexity is of the order O(M * N).
O(M * N), where 'M' is the number of rows and 'N' is the number of columns in the matrix 'A'.
In the worst case, the queue can hold the positions of all cells in the matrix. Thus, the overall space complexity is of the order O(M * N).