[LeetCode] Image Smoother

아르당·2026년 2월 12일

LeetCode

목록 보기
146/213
post-thumbnail

문제를 이해하고 있다면 바로 풀이를 보면 됨
전체 코드로 바로 넘어가도 됨
마음대로 번역해서 오역이 있을 수 있음

Problem

image smoother는 3 X 3 크기의 필터로, 이미지의 각 셀에 적용할 수 있다. smoother는 해당 셀과 주면 8개 셀의 평균값을 내림하여 계산한다(예: 파란 smoother에서는 9개 셀의 평균값). 만약 특정 셀 주변의 셀 중 하나 이상이 존재하지 않는 경우, 해당 셀은 평균 계산에서 제외된다(예: 빨간 somoother에서는 4개 셀의 평균값).

이미지의 회색조를 나타내는 m X n 크기의 정수 행렬 img가 주어졌을 때, 행렬의 각 셀에 스무딩을 적용한 후의 이미지를 반환해라.

Example

#1

Input: img = [[1, 1, 1], [1, 0, 1], [1, 1, 1]]
Output: [[0, 0, 0], [0, 0, 0], [0, 0, 0]]

#2

Input: img = [[100, 200, 100], [200, 50, 200], [100, 200, 100]]
Output: [[137, 141, 137], [141, 138, 141], [137, 141, 137]]

Constraints

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

Solved

class Solution {
    public int[][] imageSmoother(int[][] img) {
        int rows = img.length;
        int cols = img[0].length;
        int[][] result = new int[rows][cols];

        for(int row = 0; row < rows; row++){
            for(int col = 0; col < cols; col++){
                result[row][col] = average(img, row, col, rows, cols);
            }
        }

        return result;
    }

    private int average(int[][] img, int row, int col, int rows, int cols){
        int total = 0;
        int count = 0;
        int top = Math.max(0, row - 1);
        int bottom = Math.min(rows, row + 2);
        int left = Math.max(0, col - 1);
        int right = Math.min(cols, col + 2);

        for(int r = top; r < bottom; r++){
            for(int c = left; c < right; c++){
                total += img[r][c];
                count++;
            }
        }

        return total / count;
    }
}
profile
내 마음대로 코드 작성하는 세상

0개의 댓글