图片平滑器
难度:简单
根据题意模拟过程,遍历每个单元格,计算求得附近单元格的平均值即可
代码如下:
int[][] dirs = new int[][]{{0,0},{0,1},{0,-1},{1,0},{1,-1},{1,1},{-1,0},{-1,-1},{-1,1}};
public int[][] imageSmoother(int[][] img) {
int n = img.length;
int m = img[0].length;
int[][] res = new int[n][m];
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
int cnt = 0;
int times = 0;
for (int[] dir : dirs) {
int x = dir[0];
int y = dir[1];
int nx = i+x;
int ny = j+y;
if (nx >= 0 && ny >= 0 && nx < n && ny < m){
cnt += img[nx][ny];
times++;
}
}
res[i][j] = cnt/times;
}
}
return res;
}
执行结果:成功