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.
1#include <stdlib.h>
2#include <string.h>
3#include <math.h>
4
5void imageSmoother(int** M, int MSize, int* MColSize, int** returnColumnSizes) {
6 int** res = malloc(MSize * sizeof(int*));
7 (*returnColumnSizes) = malloc(MSize * sizeof(int));
8 for (int i = 0; i < MSize; ++i) {
9 res[i] = malloc((*MColSize) * sizeof(int));
10 (*returnColumnSizes)[i] = *MColSize;
11 for (int j = 0; j < *MColSize; ++j) {
12 int sum = 0, count = 0;
13 for (int ni = i - 1; ni <= i + 1; ++ni) {
14 for (int nj = j - 1; nj <= j + 1; ++nj) {
15 if (ni >= 0 && ni < MSize && nj >= 0 && nj < *MColSize) {
16 sum += M[ni][nj];
17 ++count;
18 }
19 }
20 }
21 res[i][j] = floor((float)sum / count);
22 }
23 }
24}
The solution iterates through the matrix, and for each element, it checks all possible neighbors (a total of 9 when considering the center). We keep track of sum and count to calculate the average for valid neighbors. Floor function is used to compute the rounded down result.
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// Currently not provided for C# due to technical difficulty of efficiently implementing the sliding technique.
A full C# implementation accounting for efficient in-memory sliding is deferred due to technical reasons.