题目
Given a 2D integer matrix M representing the gray scale of an image, you need to design a smoother to make the gray scale of each cell becomes the average gray scale (rounding down) of all the 8 surrounding cells and itself. If a cell has less than 8 surrounding cells, then use as many as you can.
Example 1:
Input: [[1,1,1], [1,0,1], [1,1,1]] Output: [[0, 0, 0], [0, 0, 0], [0, 0, 0]] Explanation: For the point (0,0), (0,2), (2,0), (2,2): floor(3/4) = floor(0.75) = 0 For the point (0,1), (1,0), (1,2), (2,1): floor(5/6) = floor(0.83333333) = 0 For the point (1,1): floor(8/9) = floor(0.88888889) = 0
Note:
- The value in the given matrix is in the range of [0, 255].
- The length and width of the given matrix are in the range of [1, 150].
题目大意:
给一个二维数组M,其中存放的信息为图像的灰度,对二维数组的灰度值做平滑处理,处理方式为:每个元素为其周围九宫格内值的平均值。
解决思路:
1.首先考虑一下输入值M的情况 :
(1)M可能为NULL,那么直接返回M;
(2)M的长度为0,直接返回M
(3)M是一个包含多个元素的灰度值数组。
2.在处理的时候,自己过多的考虑了一种情况,就是每个M[row]的元素长度是不相等的,但是,如果回归到所给的实际题目来说,如果M表示的图形灰度,那么每个M[row]的元素长度是相等的,所以这个考虑实属多虑。
3.很显然,是需要遍历M的每个元素的,那么就会用到嵌套的循环,在使用循环的遍历数组的时候,注意下标溢出的问题。
4.本条为整个解决思路的核心了,我们在第3条的基础上,遍历得到每个元素不是最终的目的,最终的目的是获得每个元素周围9宫格的数值(使用嵌套循环),并且知道九宫格每个位置上值的情况(有/无)。所以我们在得到每个元素的时候,就先设置一个计数变量count,求和变量sum,然后查看九宫格中的数值,如果该位置上无值,那么count--,如果该位置上有值,那么sum+=M[R][C]。
java代码实现:
class Solution{
public int[][] imageSmoother(int[][] M){
int count = 9;
int sum = 0;
if(M != null && M.length != 0) {//输入的二维数组不是空,且输入的数组长度不为0
int row = M.length;//二维数组的行
int col = M[0].length;//二维数组的列
int[][] res = new int[row][col];//存放平滑处理后的信息
for(int i = 0 ; i< row ;i++) {
for(int j = 0;j<M[i].length;j++) {//嵌套for循环遍历M的每个元素
//对sum和count的重新赋值,避免上个元素的sum和count对当前元素的sum和count的影响
sum = 0;
count = 9;
//下面的for循环实际是为了获得每个元素的“九宫格”
for(int R = i-1;R<i+2;R++) {
for(int C= j-1;C<j+2;C++) {
if(R < 0 || R > row -1) {
count--;//如果当前位置无效,则count--
continue;
}else {
col = M[R].length;
if(C < 0 || C > col -1) {
count--;//如果当前位置无效,则count--
continue;
}else {
sum += M[R][C];
}
}
}
res[i][j] = sum/count;
}
}
}
return res;
}
return M;
}
}