Leetcode 661.图片平滑器

图片平滑器

包含整数的二维矩阵 M 表示一个图片的灰度。你需要设计一个平滑器来让每一个单元的灰度成为平均灰度 (向下舍入) ,平均灰度的计算是周围的8个单元和它本身的值求平均,如果周围的单元格不足八个,则尽可能多的利用它们。

示例 1:

输入:

[[1,1,1],

[1,0,1],

[1,1,1]]

输出:

[[0, 0, 0],

[0, 0, 0],

[0, 0, 0]]

解释:

对于点 (0,0), (0,2), (2,0), (2,2): 平均(3/4) = 平均(0.75) = 0

对于点 (0,1), (1,0), (1,2), (2,1): 平均(5/6) = 平均(0.83333333) = 0

对于点 (1,1): 平均(8/9) = 平均(0.88888889) = 0

注意:

  1. 给定矩阵中的整数范围为 [0, 255]。
  2. 矩阵的长和宽的范围均为 [1, 150]。

思路

  题目给了我们一个2d M array,让我们平滑处理图片。对于每一个cell,把它更新为 以自身为中心 3x3 的平均值。

  就用常规方法做,新设一个 res[][] array,遍历M,对于每一个cell, 遍历以它为中心的3x3的cells,得到平均值,存入res。

  需要注意的就是,3x3的边界问题。

 

 1 class Solution
 2 {
 3     public int[][] imageSmoother(int[][] M)
 4     {
 5         int rows = M.length;
 6         int cols = M[0].length;
 7         int[][] res = new int[rows][cols];
 8 
 9         for(int i=0; i<rows; i++)
10         {
11             for(int j=0; j<cols; j++)
12             {
13                 int sum = 0;
14                 int count = 0;
15                 // sum 3x3 area and take care of the boundary
16                 for(int x=Math.max(0,i-1); x<=Math.min(rows-1, i+1); x++)
17                 {
18                     for(int y=Math.max(0, j-1); y<=Math.min(cols-1, j+1); y++)
19                     {
20                         sum += M[x][y]; // sum up cells value
21                         count++; // count cells number
22                     }
23                 }
24 
25                 res[i][j] = sum / count; // get average value
26             }
27         }
28 
29         return res;
30     }
31 }

 

 

原文地址:https://www.cnblogs.com/kexinxin/p/10394914.html