Leetcode PHP题解--D123 661. Image Smoother

码农天地 -
Leetcode PHP题解--D123 661. Image Smoother
D123 661. Image Smoother题目链接

661. Image Smoother

题目分析

给定一个二维数组,每一项需要是其周围值的平均值向下取整。

思路

我的做法比较直接,获取周围的值,计算周围元素的个数及其值,取得平均值,填充进新数组就好了。

最终代码
<?php
class Solution {

    /**
     * @param Integer[][] $M
     * @return Integer[][]  
     */
    function imageSmoother($M) {
        $N = $M;
        foreach($N as $row => $v){
            foreach($v as $col => $v1){
                //upRow
                $suroundedValues = [
                    isset($M[$row-1][$col-1]) ? $M[$row-1][$col-1] : null,
                    isset($M[$row-1][$col  ]) ? $M[$row-1][$col  ] : null,
                    isset($M[$row-1][$col+1]) ? $M[$row-1][$col+1] : null,
                    
                    isset($M[$row  ][$col-1]) ? $M[$row  ][$col-1] : null,

                    isset($M[$row  ][$col+1]) ? $M[$row  ][$col+1] : null,
                    
                    isset($M[$row+1][$col-1]) ? $M[$row+1][$col-1] : null,
                    isset($M[$row+1][$col  ]) ? $M[$row+1][$col  ] : null,
                    isset($M[$row+1][$col+1]) ? $M[$row+1][$col+1] : null,
                ];
                
                $filteredValues = array_filter($suroundedValues, function($values){
                    return !is_null($values);
                });
                $filteredValues[] = $v1;
                $N[$row][$col] = floor(array_sum($filteredValues)/count($filteredValues));
            }
        }
        return $N;
    }
}

若觉得本文章对你有用,欢迎用爱发电资助。

特别申明:本文内容来源网络,版权归原作者所有,如有侵权请立即与我们联系(cy198701067573@163.com),我们将及时处理。

php介绍

PHP即“超文本预处理器”,是一种通用开源脚本语言。PHP是在服务器端执行的脚本语言,与C语言类似,是常用的网站编程语言。PHP独特的语法混合了C、Java、Perl以及 PHP 自创的语法。利于学习,使用广泛,主要适用于Web开发领域。

Tags 标签

leetcodephp

扩展阅读

加个好友,技术交流

1628738909466805.jpg