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.
1var imageSmoother = function(M) {
2 const m = M.length, n = M[0].length;
3 const res = Array.from({ length: m }, () => Array(n).fill(0));
4 const dirs = [[-1, -1], [-1, 0], [-1, 1], [0, -1], [0, 0], [0, 1], [1, -1], [1, 0], [1, 1]];
5
6 for (let i = 0; i < m; i++) {
7 for (let j = 0; j < n; j++) {
8 let sum = 0, count = 0;
9 for (let [di, dj] of dirs) {
10 const ni = i + di, nj = j + dj;
11 if (ni >= 0 && ni < m && nj >= 0 && nj < n) {
12 sum += M[ni][nj];
13 count++;
14 }
15 }
16 res[i][j] = Math.floor(sum / count);
17 }
18 }
19 return res;
20};
The JavaScript solution makes use of array methods for matrix creation and incorporates direction offsets in nested loops to sum valid neighboring values efficiently.
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.
1
The Python version attempts a naive version of the sliding process, using nested directional offsets for maintaining a tally.