imajinyun /
leetcode-php
| 1 | <?php |
||
| 2 | |||
| 3 | declare(strict_types=1); |
||
| 4 | |||
| 5 | namespace leetcode; |
||
| 6 | |||
| 7 | class RangeSumQuery2DImmutable |
||
| 8 | { |
||
| 9 | private array $matrix; |
||
| 10 | private array $dp; |
||
| 11 | |||
| 12 | public function __construct(array $matrix) |
||
| 13 | { |
||
| 14 | $this->matrix = $matrix; |
||
| 15 | [$m, $n] = [count($matrix), is_array($matrix[0]) ? count($matrix[0]) : 0]; |
||
| 16 | if (!$matrix || $m <= 0 || $n <= 0) { |
||
|
0 ignored issues
–
show
|
|||
| 17 | return 0; |
||
| 18 | } |
||
| 19 | $this->dp = array_fill(0, $m + 1, array_fill(0, $n + 1, 0)); |
||
| 20 | for ($i = 1; $i <= $m; $i++) { |
||
| 21 | for ($j = 1; $j <= $n; $j++) { |
||
| 22 | $this->dp[$i][$j] = $this->dp[$i - 1][$j] |
||
| 23 | + $this->dp[$i][$j - 1] |
||
| 24 | - $this->dp[$i - 1][$j - 1] |
||
| 25 | + $this->matrix[$i - 1][$j - 1]; |
||
| 26 | } |
||
| 27 | } |
||
| 28 | } |
||
| 29 | |||
| 30 | public function sumRegion(int $left, int $top, int $right, int $bottom): int |
||
| 31 | { |
||
| 32 | $left++; |
||
| 33 | $top++; |
||
| 34 | $right++; |
||
| 35 | $bottom++; |
||
| 36 | |||
| 37 | return $this->dp[$right][$bottom] |
||
| 38 | - $this->dp[$right][$top - 1] |
||
| 39 | - $this->dp[$left - 1][$bottom] |
||
| 40 | + $this->dp[$left - 1][$top - 1]; |
||
| 41 | } |
||
| 42 | } |
||
| 43 |
This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.
Consider making the comparison explicit by using
empty(..)or! empty(...)instead.