You are given an m x n integer matrix image representing pixel intensities. Some pixels are corrupted and have a value of -1.
Sanitize the image by replacing every corrupted pixel with the rounded-down average (integer division) of its valid (non-corrupted) 4-directional neighbors (up, down, left, right). If a corrupted pixel has no valid neighbors, replace it with 0.
All corrupted pixels must be computed simultaneously based on the original matrix, meaning a newly sanitized value should not influence other corrupted pixels in the same pass. Return the sanitized matrix.
Function Signature
def sanitize_image(image: list[list[int]]) -> list[list[int]]:
Rules
-
A neighbor is valid when it lies inside the matrix and its original value is not
-1
. A pixel that was corrupted never counts as a valid neighbor, even after it has been replaced.
-
Pixels that are not corrupted keep their value. A valid pixel with value
0
still counts as a neighbor.
-
The average is the sum of the valid neighbors divided by their count, rounded down. Valid values are never negative, so this is plain integer division.
Constraints
-
m == len(image)
-
n == len(image[i])
-
1 <= m, n <= 100
-
image[i][j] == -1
or
0 <= image[i][j] <= 255
Examples
Input: image = [[10,-1,20],[-1,30,-1],[40,-1,50]]
Output: [[10,20,20],[26,30,33],[40,40,50]]
The corrupted pixel at (0,1) has valid neighbors 10, 20 and 30, so it becomes 60 // 3 = 20. The same rule gives 80 // 3 = 26 at (1,0), 100 // 3 = 33 at (1,2) and 120 // 3 = 40 at (2,1).
Input: image = [[-1,-1],[-1,-1]]
Output: [[0,0],[0,0]]
Every neighbor of every pixel is corrupted, so no pixel has a valid neighbor and all of them become 0.
Input: image = [[-1,-1,9]]
Output: [[0,9,9]]
In the original matrix, (0,0) has only the corrupted neighbor (0,1), so it becomes 0, and (0,1) has the single valid neighbor 9, so it becomes 9. Updating in place from left to right would let the new 0 at (0,0) pull (0,1) down to (0 + 9) // 2 = 4.