Created
August 20, 2018 01:19
-
-
Save jianminchen/88cedd0d3101a30288415ba23a750096 to your computer and use it in GitHub Desktop.
Leetcode 661 - image smoother - I learn the algorithm from the blog.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Analysis and source code from the blog: | |
https://koalatree.github.io/2017/10/23/LeetCode-661%EF%BC%9AImage%20Smoother%20(%E7%81%B0%E5%BA%A6%E5%9B%BE%E5%83%8F%E5%B9%B3%E6%BB%91)/ | |
问题解析: | |
给定表示图像灰度的二维整数矩阵M,平滑图像,使每个单元格的灰度值成为所有包括周围8个单元格及其本身的平均灰度(舍入)。 | |
如果周围的单元格小于8个,则使用尽可能多的单元格。 | |
Answer | |
Solution 1: | |
题目简单,遍历实现即可。 | |
对于这样的题目,我们一般来说第一反应是对每个点分三种情况进行讨论,处于角落的点用4个平滑,处于边的点用6个平滑,其它点 | |
用9个平滑。 | |
虽然上面直观的想法的算法运行时间可能不会很高,但是在实现上比较繁琐,这里我们换一个角度考虑。对于每一个点(暂时不考虑 | |
边角处点),计算该点的平滑时,共需要计算其本身及周围的9个点,也就是在该点的基础上在行和列上分别进行{-1,0,1}的索引计算, | |
实现从左上角(-1,1)到右下角(1,1)的全部位置索引。我们用两个这样的for循环来实现。在进行计算前加入一个判断函数,来判断 | |
这样的点是否超出矩阵范围,如果超出则不进行计算。 | |
题目价值不高,理解就可以。 | |
class Solution { | |
public int[][] imageSmoother(int[][] M) { | |
if (M == null) return null; | |
int rows = M.length; | |
if (rows == 0) return new int[0][]; | |
int cols = M[0].length; | |
int result[][] = new int[rows][cols]; | |
for (int row = 0; row < rows; row++){ | |
for (int col = 0; col < cols; col++){ | |
int count = 0; | |
int sum = 0; | |
for (int rInc : new int[]{-1, 0, 1}){ | |
for (int cInc : new int[]{-1, 0, 1}){ | |
if (isValid(row + rInc, col + cInc, rows, cols)){ | |
count++; | |
sum += M[row + rInc][col + cInc]; | |
} | |
} | |
} | |
result[row][col] = sum / count; | |
} | |
} | |
return result; | |
} | |
private boolean isValid(int x, int y, int rows, int cols){ | |
return x >=0 && x < rows && y >=0 && y < cols; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment