UniquePathsII::uniquePathsWithObstacles2()   A
last analyzed

Complexity

Conditions 6
Paths 5

Size

Total Lines 19
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
eloc 12
c 2
b 0
f 0
dl 0
loc 19
rs 9.2222
cc 6
nc 5
nop 1
1
<?php
2
3
declare(strict_types=1);
4
5
namespace leetcode;
6
7
class UniquePathsII
8
{
9
    public static function uniquePathsWithObstacles(array $grids): int
10
    {
11
        [$m, $n] = [count($grids), count($grids[0])];
12
        if ($m <= 0 || $n <= 0) {
13
            return 0;
14
        }
15
        $dp = array_fill(0, $m, array_fill(0, $n, 0));
16
        $dp[0][1] = 1;
17
        for ($i = 1; $i < $m; $i++) {
18
            for ($j = 1; $j < $n; $j++) {
19
                $dp[$i][$j] = $dp[$i - 1][$j] + $dp[$i][$j - 1];
20
            }
21
        }
22
23
        return $dp[$m - 1][$n - 1];
24
    }
25
26
    public static function uniquePathsWithObstacles2(array $grids): int
27
    {
28
        [$m, $n] = [count($grids), count($grids[0])];
29
        if ($m <= 0 || $n <= 0) {
30
            return 0;
31
        }
32
        $dp = array_fill(0, $n, 0);
33
        $dp[0] = 1;
34
        foreach ($grids as $grid) {
35
            for ($j = 1; $j < $n; $j++) {
36
                if ($grid[$j] === 1) {
37
                    $dp[$j] = 0;
38
                } else {
39
                    $dp[$j] += $dp[$j - 1];
40
                }
41
            }
42
        }
43
44
        return $dp[$n - 1];
45
    }
46
}
47