|
| 1 | +package com.fishercoder.solutions; |
| 2 | + |
| 3 | +/** |
| 4 | + * 661. Image Smoother |
| 5 | + * |
| 6 | + * Given a 2D integer matrix M representing the gray scale of an image, |
| 7 | + * you need to design a smoother to make the gray scale of each cell becomes the average gray scale (rounding down) of |
| 8 | + * all the 8 surrounding cells and itself. If a cell has less than 8 surrounding cells, then use as many as you can. |
| 9 | +
|
| 10 | + Example 1: |
| 11 | + Input: |
| 12 | + [[1,1,1], |
| 13 | + [1,0,1], |
| 14 | + [1,1,1]] |
| 15 | +
|
| 16 | + Output: |
| 17 | + [[0, 0, 0], |
| 18 | + [0, 0, 0], |
| 19 | + [0, 0, 0]] |
| 20 | +
|
| 21 | + Explanation: |
| 22 | + For the point (0,0), (0,2), (2,0), (2,2): floor(3/4) = floor(0.75) = 0 |
| 23 | + For the point (0,1), (1,0), (1,2), (2,1): floor(5/6) = floor(0.83333333) = 0 |
| 24 | + For the point (1,1): floor(8/9) = floor(0.88888889) = 0 |
| 25 | +
|
| 26 | + Note: |
| 27 | + The value in the given matrix is in the range of [0, 255]. |
| 28 | + The length and width of the given matrix are in the range of [1, 150]. |
| 29 | +
|
| 30 | + */ |
| 31 | +public class _661 { |
| 32 | + public int[][] imageSmoother(int[][] M) { |
| 33 | + if (M == null || M.length == 0) return M; |
| 34 | + int m = M.length; |
| 35 | + int n = M[0].length; |
| 36 | + int[][] result = new int[m][n]; |
| 37 | + for (int i = 0; i < m; i++) { |
| 38 | + for (int j = 0; j < n; j++) { |
| 39 | + bfs(M, i, j, result, m, n); |
| 40 | + } |
| 41 | + } |
| 42 | + return result; |
| 43 | + } |
| 44 | + |
| 45 | + private void bfs(int[][] M, int i, int j, int[][] result, int m, int n) { |
| 46 | + int sum = M[i][j]; |
| 47 | + int denominator = 1; |
| 48 | + if (j + 1 < n) { |
| 49 | + sum += M[i][j + 1]; |
| 50 | + denominator++; |
| 51 | + } |
| 52 | + if (i + 1 < m && j + 1 < n) { |
| 53 | + sum += M[i + 1][j + 1]; |
| 54 | + denominator++; |
| 55 | + } |
| 56 | + if (i + 1 < m) { |
| 57 | + sum += M[i + 1][j]; |
| 58 | + denominator++; |
| 59 | + } |
| 60 | + if (i + 1 < m && j - 1 >= 0) { |
| 61 | + sum += M[i + 1][j - 1]; |
| 62 | + denominator++; |
| 63 | + } |
| 64 | + if (j - 1 >= 0) { |
| 65 | + sum += M[i][j - 1]; |
| 66 | + denominator++; |
| 67 | + } |
| 68 | + if (i - 1 >= 0 && j - 1 >= 0) { |
| 69 | + sum += M[i - 1][j - 1]; |
| 70 | + denominator++; |
| 71 | + } |
| 72 | + if (i - 1 >= 0) { |
| 73 | + sum += M[i - 1][j]; |
| 74 | + denominator++; |
| 75 | + } |
| 76 | + if (i - 1 >= 0 && j + 1 < n) { |
| 77 | + sum += M[i - 1][j + 1]; |
| 78 | + denominator++; |
| 79 | + } |
| 80 | + result[i][j] = sum / denominator; |
| 81 | + } |
| 82 | +} |
0 commit comments