Image Smoother
给一个2D数组M, 返回M中每个点的均值, 均值是把周围尽可能多的点的值加起来, 然后取平均数.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 |
class Solution { public int[][] imageSmoother(int[][] M) { int[][] res = new int[M.length][M[0].length]; int[][] dirs = new int[][]{ {0,0}, {1,0}, {1,1}, {0,1}, {-1,0}, {0,-1}, {-1,-1}, {-1, 1}, {1, -1} }; for(int i = 0; i < M.length; i++) { for(int j = 0 ; j < M[0].length; j++) { int count = 0; int sum = 0; for(int[] d : dirs) { int r = d[0] + i; int c = d[1] + j; if(0 <= r && r < M.length && 0 <= c && c < M[0].length) { count ++; sum += M[r][c]; } } res[i][j] = sum / count; } } return res; } } |