题目地址:
https://leetcode.com/problems/image-smoother/
给定一个二维矩阵 M M M,返回一个新矩阵 A A A,使得 A [ i ] [ j ] A[i][j] A[i][j]是 M [ i ] [ j ] M[i][j] M[i][j]的 8 8 8个邻居及其自己的平均值(向下取整)。如果不足 8 8 8个邻居,有多少个算多少个。
代码如下:
public class Solution {
public int[][] imageSmoother(int[][] M) {
int[][] res = new int[M.length][M[0].length];
for (int i = 0; i < M.length; i++) {
for (int j = 0; j < M[i].length; j++) {
int sum = 0, count = 0;
for (int dx = -1; dx <= 1; dx++) {
for (int dy = -1; dy <= 1; dy++) {
if (0 <= i + dx && i + dx < M.length && 0 <= j + dy && j + dy < M[0].length) {
sum += M[i + dx][j + dy];
count++;
}
}
}
res[i][j] = sum / count;
}
}
return res;
}
}
时空复杂度 O ( m n ) O(mn) O(mn)。