-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathUniquePathsII.php
46 lines (40 loc) · 1.09 KB
/
UniquePathsII.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
<?php
declare(strict_types=1);
namespace leetcode;
class UniquePathsII
{
public static function uniquePathsWithObstacles(array $grids): int
{
[$m, $n] = [count($grids), count($grids[0])];
if ($m <= 0 || $n <= 0) {
return 0;
}
$dp = array_fill(0, $m, array_fill(0, $n, 0));
$dp[0][1] = 1;
for ($i = 1; $i < $m; $i++) {
for ($j = 1; $j < $n; $j++) {
$dp[$i][$j] = $dp[$i - 1][$j] + $dp[$i][$j - 1];
}
}
return $dp[$m - 1][$n - 1];
}
public static function uniquePathsWithObstacles2(array $grids): int
{
[$m, $n] = [count($grids), count($grids[0])];
if ($m <= 0 || $n <= 0) {
return 0;
}
$dp = array_fill(0, $n, 0);
$dp[0] = 1;
foreach ($grids as $grid) {
for ($j = 1; $j < $n; $j++) {
if ($grid[$j] === 1) {
$dp[$j] = 0;
} else {
$dp[$j] += $dp[$j - 1];
}
}
}
return $dp[$n - 1];
}
}