661. smoother picture

The two-dimensional matrix contains an integer M represents a gray-scale image. You need to design to make a smoother gradation of each unit becomes the average grayscale (rounding down), calculating the average gray scale value of averaging is eight units around its own and, if the surrounding cell deficiency eight, then use them as much as possible.

Example 1:

Input: 
[[1,1,1], 
 [1,0,1], 
 [1,1,1]] Output: 
[[0, 0, 0], 
 [0, 0, 0], 
 [0, 0 , 0]] explanation: 
for point (0,0), (0,2), (2,0), (2,2): the average (3/4) = mean (0.75) = 0 
for point (0, 1), (1,0), (1,2), (2,1): the average (5/6) = mean (0.83333333) = 0 
for point (1, 1): average (8/9) = mean (0.88888889) = 0


note:

  1. A is an integer in the range of a given matrix is ​​[0, 255].
  2. Long and wide range of matrices are [1, 150].
class Solution {
    public int[][] imageSmoother(int[][] M) {
        if(M==null || M.length == 0 || M[0].length == 0){
            return M;
        }
        int[][] matrix = new int[M.length][M[0].length];
        for(int i=0;i<M.length;++i){
            for(int j=0;j<M[0].length;++j){
                matrix[i][j] = calValue(M,i,j);
            }
        }
        return matrix;
    }
    
    private int calValue(int[][] M, int i, int j){
        int sum = M[i][j];
        int count = 1;
        if(validateLoc(M, i+1, j)){
            sum+=M[i+1][j];
            ++count;
        }
        if(validateLoc(M, i-1, j)){
            sum+=M[i-1][j];
            ++count;
        }
        if(validateLoc(M, i+1, j+1)){
            sum+=M[i+1][j+1];
            ++count;
        }
        if(validateLoc(M, i+1, j-1)){
            sum+=M[i+1][j-1];
            ++count;
        }
        if(validateLoc(M, i-1, j+1)){
            sum+=M[i-1][j+1];
            ++count;
        }
        if(validateLoc(M, i-1, j-1)){
            sum+=M[i-1][j-1];
            ++count;
        }
        if(validateLoc(M, i, j-1)){
            sum+=M[i][j-1];
            ++count;
        }
        if(validateLoc(M, i, j+1)){
            sum+=M[i][j+1];
            ++count;
        }
        return sum/count;
    }
    
    private boolean validateLoc(int[][] M, int i,int j){
        if(i<0||i>=M.length||j<0||j>=M[0].length){
            return false;
        }
        return true;
    }
}

 

Published 106 original articles · won praise 16 · views 40000 +

Guess you like

Origin blog.csdn.net/qq_35356190/article/details/83478973