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) = 0For the point (0,1), (1,0), (1,2), (2,1): floor(5/6) = floor(0.83333333) = 0For 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].
1 class Solution { 2 public int[][] imageSmoother(int[][] M) { 3 int m = M.length, n = M[0].length; 4 int result[][] = new int[m][n]; 5 6 for (int i = 0; i < m; i++) { 7 for (int j = 0; j < n; j++) { 8 int[] surroundings = countSurroundings(M, i, j); 9 result[i][j] = surroundings[0] / surroundings[1];10 }11 }12 13 return result;14 }15 16 private int[] countSurroundings(int[][] M, int i, int j) {17 int result[] = {0, 0}; // surroundingCount, surroundingNumber18 for (int ii = i - 1; ii <= i + 1; ii++) {19 for (int jj = j - 1; jj <= j + 1; jj++) {20 if (ii < 0 || jj < 0 || ii >= M.length || jj >= M[0].length) {21 continue;22 } else {23 result[1] += 1;24 result[0] += M[ii][jj];25 }26 }27 }28 29 return result;30 }31 }