넘치게 채우기

[LeetCode] 661. Image Smoother 본문

PS/LeetCode

[LeetCode] 661. Image Smoother

riveroverflow 2023. 12. 19. 12:25
728x90
반응형

https://leetcode.com/problems/image-smoother/description/

 

Image Smoother - LeetCode

Can you solve this real interview question? Image Smoother - 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 nin

leetcode.com

leetcode - Image Smoother

문제 유형 : 행렬

문제 난이도 : Easy

 

 

문제

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.

 

이미지 스무터는 이미지의 3x3의 범위에서 중앙 셀에서 상하좌우 대각선으로 인접한 셀들과의 평균을 구해서 round down하는 기능입니다. 범위가 셀 밖에 나가면, 그 부분은 제외합니다.

 

 

m x n의 크기의 이미지의 회색조를 담은 정수 행렬 Img가 주어집니다. 이미지의 각 행에 스무터를 적용시킨 것을 반환하시오.

 

 

풀이

같은 m x n의 크기의 빈 행렬을 만들어준다.

2중 반복문으로 배열을 순회하면서, 각각의 셀에서 이미지 스무터를 사용한 값을 저장시키고 반환한다.

 

이미지 스무터의 구현은 다음과 같이 할 수 있다: 

현재 셀에서 각 행과 열을 (-1, -1), (0, -1), (1, -1), (-1, 0), (0, 0), (1, 0), (-1, 1), (0, 1), (1, 1) 이동시킨 후, 만약 범위를 벗어나면 계산하지 않고, 범위 내라면 셀의 수와 누적 합을 구한 다음, 나눠서 평균을 구해준 뒤 반환해주면 된다.

 

 

코드

C++

static const int __ = [](){
    ios_base::sync_with_stdio(0);
    cin.tie(0);
    cout.tie(0);
    return 0;
}();

class Solution {
private:
    vector<int> d = {-1, 0, 1};
public:
    int getScale(int row, int col, vector<vector<int>> &image) {
        int sum = 0;
        int cnt = 0;
        for(int i = 0; i < 3; i++) {
            for(int j = 0; j < 3; j++) {
                int newRow = row + d[i];
                int newCol = col + d[j];
                if(newRow < 0 || newRow >= image.size() || newCol < 0 || newCol >= image[0].size()) continue;
                cnt++;
                sum+= image[newRow][newCol];
            }
        }
        return sum / cnt;
    }

    vector<vector<int>> imageSmoother(vector<vector<int>>& img) {
        const int m = img.size();
        const int n = img[0].size();

        vector<vector<int>> newImg(m, vector<int>(n, 0));

        for(int i = 0; i < m; i++) {
            for(int j = 0; j < n; j++) {
                newImg[i][j] = getScale(i, j, img);
            }
        }

        return newImg;
    }
};
 
728x90
반응형