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 <vector>
2#include <cmath>
3using namespace std;
4
5vector<vector<int>> imageSmoother(vector<vector<int>>& M) {
6 int m = M.size(), n = M[0].size();
7 vector<vector<int>> res(m, vector<int>(n, 0));
8 vector<vector<int>> dirs = {{-1, -1}, {-1, 0}, {-1, 1}, {0, -1}, {0, 0}, {0, 1}, {1, -1}, {1, 0}, {1, 1}};
9
10 for (int i = 0; i < m; ++i) {
11 for (int j = 0; j < n; ++j) {
12 int sum = 0, count = 0;
13 for (auto d : dirs) {
14 int ni = i + d[0], nj = j + d[1];
15 if (ni >= 0 && ni < m && nj >= 0 && nj < n) {
16 sum += M[ni][nj];
17 ++count;
18 }
19 }
20 res[i][j] = floor(sum / count);
21 }
22 }
23 return res;
24}
In this implementation, the relative positions for all 9 neighboring cells are stored in a 'dirs' array. We loop through these positions for each cell, checking for validity, thereby accumulating the sum and count of valid neighbors to compute their average.
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// No C implementation for optimized sliding window approach available.
Unfortunately, a C implementation using a sophisticated sliding window for this problem context is not readily available.