LeetCode 661. Image Smoother
阿新 • • 發佈:2018-12-12
一、問題描述
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.
Example1
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) = 0
For the point (0,1), (1,0), (1,2), (2,1): floor(5/6) = floor(0.83333333) = 0
For 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].
二、題意分析
將二維矩陣中每一個元素的值,設定為以當前元素為中心的3*3區域的平均值。若周圍沒有9個元素(落在四條邊上),則有多少計算多少個。
三、解題思路一
最開始的思路是,在矩陣周圍圍上一圈值為0的牆,計算每一個元素3*3區域的累加和,然後統計出的每個元素周圍所含元素的個數(不包含牆值),最後計算個平均值就可以了。 但是,這樣做的時候我在統計每個元素周圍的元素個數時,有些麻煩。
程式碼實現
class Solution {
public int[][] imageSmoother(int[][] M) {
int row = M.length, col = M[ 0].length;
System.out.println("row : " + row);
System.out.println("col : " + col);
int[][] result = new int[row+2][col + 2];
// 給矩陣周圍加一圈0,方便計算
for(int i = 0; i < row+2; i++){
for(int j = 0; j < col+2; j++){
if(i == 0 || i == row + 1){
result[i][j] = 0;
continue;
}
if(j == 0 || j == col + 1){
result[i][j] = 0;
continue;
}
result[i][j] = M[i-1][j-1];
}
}
int numbers = 9;
for(int i = 0 ; i < M.length; i++){
for(int j = 0; j < M[i].length; j++){
numbers = 9;
if((i == 0 || i == row - 1) && (j == 0 || j == col -1)){
numbers = 4;
if(row == 1 || col == 1)
numbers = 2;
if(col == 1 && row == 1)
numbers = 1;
}else if((i == 0 || i == row -1) && (0 < j && j < col - 1)){
numbers = 6;
if(row == 1 || col == 1)
numbers = 3;
}else if((j == 0 || j == col - 1) && (0 < i && i < row -1)){
numbers = 6;
if(row == 1 || col == 1)
numbers = 3;
}
M[i][j] = calculateAvg(result, i + 1, j + 1, numbers);
}
}
return M;
}
// 計算3*3區域的累加和
public static int calculateAvg(int[][] result, int i, int j, int numbers){
int sum = 0;
for(int row = i - 1; row < i+2; row++){
for(int col = j - 1; col < j+2; col++){
sum +=result[row][col];
}
}
return (int) (sum/ numbers);
}
}
時間、空間複雜度分析
- 時間複雜度
O (n2)
- 空間複雜度
O (n2)
四、解題思路二
直接暴力法解決
程式碼實現
class Solution {
public int[][] imageSmoother(int[][] M) {
int row = M.length, col = M[0].length;
int[][] result = new int[row][col];
int numbers = 0, sum = 0;
for(int i = 0; i < row; i++){
for(int j = 0; j < col; j++){
numbers = 0;
sum = 0;
for(int k = i - 1; k < i + 2; k++){
// 邊界判斷
if(k < 0 || k >= row)
continue;
for(int c = j - 1; c < j+2; c++){
// 邊界判斷
if(c < 0 || c >= col)
continue;
sum += M[k][c];
numbers++;
}
}
result[i][j] = sum / numbers;
}
}
return result;
}
}
時間、空間複雜度分析
- 時間複雜度
O (n2)
- 空間複雜度
O (1)