Sponsored
Sponsored
This approach involves iterating over each cell and calculating the sum and count of valid neighbors in the 3x3 neighborhood range. For each cell, we consider neighboring cells that exist and are within bounds.
The time complexity is O(m * n * 9), which simplifies to O(m * n) because we are only performing a fixed amount of work per cell. The space complexity is O(m * n) for storing the result matrix.
1def imageSmoother(M):
2 m, n = len(M), len(M[0])
3 res = [[0] * n for _ in range(m)]
4 dirs = [(-1, -1), (-1, 0), (-1, 1), (0, -1), (0, 0), (0, 1), (1, -1), (1, 0), (1, 1)]
5
6 for i in range(m):
7 for j in range(n):
8 total = 0
9 count = 0
10 for d in dirs:
11 ni, nj = i + d[0], j + d[1]
12 if 0 <= ni < m and 0 <= nj < n:
13 total += M[ni][nj]
14 count += 1
15 res[i][j] = total // count
16
17 return res
The Python solution iterates over each cell, gathering valid neighbor cell values using the directions list for bounds checking. It stores the result of the floored average back into the result matrix.
This approach leverages a sliding window technique within the 3x3 area, minimizing redundant calculations by reusing previously computed sums and counts from prior cells wherever applicable.
The time and space complexities remain as O(m * n) due to the sliding optimization remaining bounded per cell, though potentially with reduced constant factor.
1def
The Python version attempts a naive version of the sliding process, using nested directional offsets for maintaining a tally.