imajinyun /
leetcode-php
| 1 | <?php |
||
| 2 | |||
| 3 | declare(strict_types=1); |
||
| 4 | |||
| 5 | namespace leetcode; |
||
| 6 | |||
| 7 | class BombEnemy |
||
| 8 | { |
||
| 9 | public static function maxKilledEnemies(array $grids): int |
||
| 10 | { |
||
| 11 | [$res, $m, $n] = [0, count($grids), count($grids[0])]; |
||
| 12 | if ($m <= 0 || $n <= 0) { |
||
| 13 | return $res; |
||
| 14 | } |
||
| 15 | $v1 = $v2 = $v3 = $v4 = array_fill(0, $m, array_fill(0, $n, 0)); |
||
| 16 | for ($i = 0; $i < $m; $i++) { |
||
| 17 | for ($j = 0; $j < $n; $j++) { // 列从上到下 |
||
| 18 | $t = ($j === 0 || $grids[$i][$j] === 'W') ? 0 : $v1[$i][$j - 1]; |
||
| 19 | $v1[$i][$j] = $grids[$i][$j] === 'E' ? $t + 1 : $t; |
||
| 20 | } |
||
| 21 | for ($j = $n - 1; $j >= 0; $j--) { // 列从下到上 |
||
| 22 | $t = ($j === $n - 1 || $grids[$i][$j] === 'W') ? 0 : $v2[$i][$j + 1]; |
||
| 23 | $v2[$i][$j] = $grids[$i][$j] === 'E' ? $t + 1 : $t; |
||
| 24 | } |
||
| 25 | } |
||
| 26 | |||
| 27 | for ($j = 0; $j < $n; $j++) { |
||
| 28 | for ($i = 0; $i < $m; $i++) { // 行从左到右 |
||
| 29 | $t = ($i === 0 || $grids[$i][$j] === 'W') ? 0 : $v3[$i - 1][$j]; |
||
| 30 | $v3[$i][$j] = $grids[$i][$j] === 'E' ? $t + 1 : $t; |
||
| 31 | } |
||
| 32 | for ($i = $m - 1; $i >= 0; $i--) { // 行从右到左 |
||
| 33 | $t = ($i === $m - 1 || $grids[$i][$j] === 'W') ? 0 : $v4[$i + 1][$j]; |
||
| 34 | $v4[$i][$j] = $grids[$i][$j] === 'E' ? $t + 1 : $t; |
||
| 35 | } |
||
| 36 | } |
||
| 37 | |||
| 38 | for ($i = 0; $i < $m; $i++) { |
||
| 39 | for ($j = 0; $j < $n; $j++) { |
||
| 40 | if ($grids[$i][$j] === '0') { |
||
| 41 | $res = max($res, $v1[$i][$j] + $v2[$i][$j] + $v3[$i][$j] + $v4[$i][$j]); |
||
| 42 | } |
||
| 43 | } |
||
| 44 | } |
||
| 45 | |||
| 46 | return $res; |
||
| 47 | } |
||
| 48 | |||
| 49 | public static function maxKilledEnemies2(array $grids): int |
||
| 50 | { |
||
| 51 | [$res, $m, $n] = [0, count($grids), count($grids[0])]; |
||
| 52 | if ($m <= 0 || $n <= 0) { |
||
| 53 | return $res; |
||
| 54 | } |
||
| 55 | $col = array_fill(0, $n, 0); |
||
| 56 | for ($i = 0; $i < $m; $i++) { |
||
| 57 | for ($j = 0; $j < $n; $j++) { |
||
| 58 | if ($j === 0 || $grids[$i][$j - 1] === 'W') { |
||
| 59 | $row = 0; |
||
| 60 | for ($k = $j; $k < $n && $grids[$i][$k] !== 'W'; $k++) { |
||
| 61 | $row += $grids[$i][$k] === 'E'; |
||
| 62 | } |
||
| 63 | } |
||
| 64 | if ($i === 0 || $grids[$i - 1][$j] === 'W') { |
||
| 65 | $col[$j] = 0; |
||
| 66 | for ($k = $i; $k < $m && $grids[$k][$j] !== 'W'; $k++) { |
||
| 67 | $col[$j] += $grids[$k][$j] === 'E'; |
||
| 68 | } |
||
| 69 | } |
||
| 70 | if ($grids[$i][$j] === '0') { |
||
| 71 | $res = max($res, $row + $col[$j]); |
||
|
0 ignored issues
–
show
Comprehensibility
Best Practice
introduced
by
Loading history...
|
|||
| 72 | } |
||
| 73 | } |
||
| 74 | } |
||
| 75 | |||
| 76 | return $res; |
||
| 77 | } |
||
| 78 | } |
||
| 79 |