|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
declare(strict_types=1); |
|
4
|
|
|
|
|
5
|
|
|
namespace leetcode; |
|
6
|
|
|
|
|
7
|
|
|
class ImageSmoother |
|
8
|
|
|
{ |
|
9
|
|
|
public static function imageSmoother(array $arr): array |
|
10
|
|
|
{ |
|
11
|
|
|
if (empty($arr)) { |
|
12
|
|
|
return [[]]; |
|
13
|
|
|
} |
|
14
|
|
|
[$m, $n] = [count($arr), empty($arr[0]) ? 0 : count($arr[0])]; |
|
15
|
|
|
$ans = array_fill(0, $m, array_fill(0, $n, 0)); |
|
16
|
|
|
for ($i = 0; $i < $m; $i++) { |
|
17
|
|
|
for ($j = 0; $j < $n; $j++) { |
|
18
|
|
|
$cnt = 0; |
|
19
|
|
|
for ($row = $i - 1; $row <= $i + 1; $row++) { |
|
20
|
|
|
for ($col = $j - 1; $col <= $j + 1; $col++) { |
|
21
|
|
|
if (0 <= $row && $row < $m && 0 <= $col && $col < $n) { |
|
22
|
|
|
$ans[$i][$j] += $arr[$row][$col]; |
|
23
|
|
|
$cnt++; |
|
24
|
|
|
} |
|
25
|
|
|
} |
|
26
|
|
|
} |
|
27
|
|
|
if ($cnt > 0) { |
|
28
|
|
|
$ans[$i][$j] = (int) floor($ans[$i][$j] / $cnt); |
|
29
|
|
|
} |
|
30
|
|
|
} |
|
31
|
|
|
} |
|
32
|
|
|
|
|
33
|
|
|
return $ans; |
|
34
|
|
|
} |
|
35
|
|
|
|
|
36
|
|
|
public static function imageSmoother2(array $arr): array |
|
37
|
|
|
{ |
|
38
|
|
|
$res = [[]]; |
|
39
|
|
|
if (empty($arr)) { |
|
40
|
|
|
return $res; |
|
41
|
|
|
} |
|
42
|
|
|
|
|
43
|
|
|
foreach ($arr as $i => $item) { |
|
44
|
|
|
foreach ($item as $j => $v) { |
|
45
|
|
|
$tmp = []; |
|
46
|
|
|
|
|
47
|
|
|
// current row |
|
48
|
|
|
$tmp[] = $v; |
|
49
|
|
|
if (isset($item[$j - 1])) { |
|
50
|
|
|
$tmp[] = $item[$j - 1]; |
|
51
|
|
|
} |
|
52
|
|
|
if (isset($item[$j + 1])) { |
|
53
|
|
|
$tmp[] = $item[$j + 1]; |
|
54
|
|
|
} |
|
55
|
|
|
|
|
56
|
|
|
// previous row |
|
57
|
|
|
if (isset($arr[$i - 1][$j])) { |
|
58
|
|
|
$tmp[] = $arr[$i - 1][$j]; |
|
59
|
|
|
} |
|
60
|
|
|
if (isset($arr[$i - 1][$j - 1])) { |
|
61
|
|
|
$tmp[] = $arr[$i - 1][$j - 1]; |
|
62
|
|
|
} |
|
63
|
|
|
if (isset($arr[$i - 1][$j + 1])) { |
|
64
|
|
|
$tmp[] = $arr[$i - 1][$j + 1]; |
|
65
|
|
|
} |
|
66
|
|
|
|
|
67
|
|
|
// next row |
|
68
|
|
|
if (isset($arr[$i + 1][$j])) { |
|
69
|
|
|
$tmp[] = $arr[$i + 1][$j]; |
|
70
|
|
|
} |
|
71
|
|
|
if (isset($arr[$i + 1][$j - 1])) { |
|
72
|
|
|
$tmp[] = $arr[$i + 1][$j - 1]; |
|
73
|
|
|
} |
|
74
|
|
|
if (isset($arr[$i + 1][$j + 1])) { |
|
75
|
|
|
$tmp[] = $arr[$i + 1][$j + 1]; |
|
76
|
|
|
} |
|
77
|
|
|
$tmp = (int) floor(array_sum($tmp) / count($tmp)); |
|
78
|
|
|
$res[$i][$j] = $tmp; |
|
79
|
|
|
} |
|
80
|
|
|
} |
|
81
|
|
|
|
|
82
|
|
|
return $res; |
|
83
|
|
|
} |
|
84
|
|
|
} |
|
85
|
|
|
|