包含整數的二維矩陣 M 表示一個圖檔的灰階。你需要設計一個平滑器來讓每一個單元的灰階成為平均灰階 (向下舍入) ,平均灰階的計算是周圍的8個單元和它本身的值求平均,如果周圍的單元格不足八個,則盡可能多的利用它們。
示例 1:
輸入: [[1,1,1],
[1,0,1],
[1,1,1]]
輸出: [[0, 0, 0],
[0, 0, 0],
[0, 0,0]]
解釋: 對于點 (0,0), (0,2), (2,0), (2,2): 平均(3/4) = 平均(0.75) = 0
對于點(0,1), (1,0), (1,2), (2,1): 平均(5/6) = 平均(0.83333333) = 0
對于點 (1,1):平均(8/9) = 平均(0.88888889) = 0
注意:
給定矩陣中的整數範圍為 [0, 255]。
矩陣的長和寬的範圍均為 [1, 150]。
來源:力扣(LeetCode)
連結:https://leetcode-cn.com/problems/image-smoother
方法 1:周遊矩陣
對于矩陣中的每一個單元格,找所有 9 個包括它自身在内的緊鄰的格子。
然後,我們要将所有鄰居的和儲存在 ans[r][c] 中,同時記錄鄰居的數目 count。最終的答案就是和除以鄰居數目。
public int[][] imageSmoother(int[][] M) {
int R = M.length, C = M[0].length;
int[][] ans = new int[R][C];
for (int r = 0; r < R; r++)
for (int c = 0; c < C; c++) {
int count = 0;
for (int nr = r - 1; nr <= r + 1; nr++)
for (int nc = c - 1; nc <= c + 1; nc++) {
if (nr >= 0 && nr < R && nc >= 0 && nc < C) {
ans[r][c] += M[nr][nc];
count++;
}
}
ans[r][c] /= count;
}
return ans;
}