Categories:

Tags:



Problem

An image smoother is a filter of the size 3 x 3 that can be applied to each cell of an image by rounding down the average of the cell and the eight surrounding cells (i.e., the average of the nine cells in the blue smoother). If one or more of the surrounding cells of a cell is not present, we do not consider it in the average (i.e., the average of the four cells in the red smoother).

Given an m x n integer matrix img representing the grayscale of an image, return the image after applying the smoother on each cell of it.

Constraints

  • m == img.length
  • n == img[i].length
  • 1 <= m, n <= 200
  • 0 <= img[i][j] <= 255

Solution

The problem Image Smoother can be solved by adding adjacent cells for all cells in the matrix and calculating their average.

Implementation

class Solution
{
  public:
    vector<vector<int>> imageSmoother(vector<vector<int>> &img)
    {
        int m = img.size(), n = img[0].size();
        vector<vector<int>> ret(m, vector<int>(n, 0));

        for (int i = 0; i < m; i++)
            for (int j = 0; j < n; j++)
            {
                int sum = 0, count = 0;
                for (int di = -1; di <= 1; di++)
                    for (int dj = -1; dj <= 1; dj++)
                        if ((unsigned int)(i + di) < m && (unsigned int)(j + dj) < n)
                        {
                            sum += img[i + di][j + dj];
                            count += 1;
                        }
                ret[i][j] = sum / count;
            }

        return ret;
    }
};