领扣LintCode算法问题答案-1102. 图片平滑器
发布日期:2021-06-30 17:09:51 浏览次数:3 分类:技术文章

本文共 2306 字,大约阅读时间需要 7 分钟。

领扣LintCode算法问题答案-1102. 图片平滑器

目录

1102. 图片平滑器

描述

包含整数的二维矩阵 M 表示一个图片的灰度。你需要设计一个平滑器来让每一个单元的灰度成为平均灰度 (向下舍入) ,平均灰度的计算是周围的8个单元和它本身的值求平均,如果周围的单元格不足八个,则尽可能多的利用它们。

  1. 给定矩阵中的整数范围为 [0, 255]。
  2. 矩阵的长和宽的范围均为 [1, 150]。

样例 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

题解

public class Solution {
/** * @param M: a 2D integer matrix * @return: a 2D integer matrix */ public int[][] imageSmoother(int[][] M) {
// Write your code here if (M == null) {
return null; } int maxR = M.length; if (maxR == 0) {
return M; } int maxC = M[0].length; if (maxC == 0) {
return M; } int[][] ret = new int[maxR][maxC]; for (int r = 0; r < maxR; r++) {
for (int c = 0; c < maxC; c++) {
double totalValue = M[r][c]; int count = 1; if (r > 0) {
if (c > 0) {
totalValue += M[r-1][c-1]; count++; } totalValue += M[r-1][c]; count++; if (c + 1 < maxC) {
totalValue += M[r-1][c+1]; count++; } } if (c > 0) {
totalValue += M[r][c-1]; count++; } if (c + 1 < maxC) {
totalValue += M[r][c+1]; count++; } if (r + 1 < maxR) {
if (c > 0) {
totalValue += M[r+1][c-1]; count++; } totalValue += M[r+1][c]; count++; if (c + 1 < maxC) {
totalValue += M[r+1][c+1]; count++; } } ret[r][c] = (int) (totalValue / count); } } return ret; }}

鸣谢

非常感谢你愿意花时间阅读本文章,本人水平有限,如果有什么说的不对的地方,请指正。

欢迎各位留言讨论,希望小伙伴们都能每天进步一点点。

转载地址:https://le-yi.blog.csdn.net/article/details/108841651 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!

上一篇:领扣LintCode算法问题答案-1104. 机器人能否返回原点
下一篇:领扣LintCode算法问题答案-1099. 不下降数组

发表评论

最新留言

表示我来过!
[***.240.166.169]2024年05月02日 17时19分12秒