본문 바로가기

Algorithm/Implementation

(C++) - LeetCode (easy) 661. Image Smoother

반응형

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

 

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

구현 문제였습니다.

📕 풀이방법

📔 입력 및 초기화

1. img의 행 수 r, 열 수 c를 선언 후 저장해줍니다.2. 정답 변수 v를 2차원 vector형태로 선언해 줍니다.

📔 풀이과정

1. img의 모든 원소를 순회하면서 평균을 구해줍니다.

2. 한 행의 정보를 vector rows를 선언해 구한 평균을 넣어줍니다.

평균을 구하는 과정에서 r, c를 넘지 않도록 주의해줍니다.

📔 정답 출력 | 반환

v를 반환합니다.


📕 Code

📔 C++

class Solution {
public:
    int getAvg(int r, int c, int rLimit, int cLimit, vector<vector<int>>& img) {
        int cnt = 0;
        int sum = 0;
        for(int k = r-1; k <= r + 1; k++) {
            if(k < 0 || k >= rLimit) continue;
            for(int l = c - 1; l <= c + 1; l++) {
                if(l < 0 || l >= cLimit) continue;
                cnt++;
                sum += img[k][l];
            }
        }
        return sum / cnt;
    }
    
    vector<vector<int>> imageSmoother(vector<vector<int>>& img) {
        int r = img.size();
        int c = img[0].size();
        vector<vector<int>> v(r, vector<int>(c,0));
        for (int i = 0; i < r; i++) {
            for (int j = 0; j < c; j++) {
                int avg = getAvg(i, j, r, c, img);
                v[i][j] = avg;
            }
        }
        return v;

    }
};

*더 나은 내용을 위한 지적, 조언은 언제나 환영합니다.