包含整数的二维矩阵 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
第一个解决方案是我自己写的,第二个是选的自己认为简单,用时少的代码
class Solution {
public int[][] imageSmoother(int[][] M) {
if(M.length<=0)
return M;
int [][]R=new int[M.length][M[0].length];
for(int i=0;i<M.length;i++)
{
for(int j=0;j<M[0].length;j++)
{
int count=1;
int grey=M[i][j];
if(i-1>=0)
{
grey+=M[i-1][j];
count++;
}
if(i+1<M.length)
{
grey+= M[i+1][j];
count++;
}
if(j-1>=0)
{
grey+= M[i][j-1];
count++;
}
if(j+1<M[0].length)
{
grey+= M[i][j+1];
count++;
}
if(i-1>=0&&j-1>=0)
{
grey+=M[i-1][j-1];
count++;
}
if(i-1>=0&&j+1<M[0].length)
{
grey+= M[i-1][j+1];
count++;
}
if(i+1<M.length&&j-1>=0)
{
grey+= M[i+1][j-1];
count++;
}
if(i+1<M.length&&j+1<M[0].length)
{
grey+= M[i+1][j+1];
count++;
}
R[i][j]=grey/count;
}
}
return R;
}
}
class Solution {
public int[][] imageSmoother(int[][] M) {
int m = M.length;
int n = M[0].length;
int[][] res = new int[m][n];
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
res[i][j] = smooth(M, i, j);
}
}
return res;
}
public int smooth(int[][]M,int m,int n)
{
int mm = M.length;
int nn = M[0].length;
int count=0;
int sum=0;
for(int i=-1;i<=1;i++)
{
for(int j=-1;j<=1;j++)
{
if(m+i<0||m+i>=mm||n+j<0||n+j>=nn)
continue;
count++;
sum+=M[m+i][n+j];
}
}
return sum/count;
}
}