forked from algorithm020/algorithm020
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathminPathSum.php
More file actions
32 lines (26 loc) · 723 Bytes
/
minPathSum.php
File metadata and controls
32 lines (26 loc) · 723 Bytes
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
<?php
class Solution {
/**
* @param Integer[][] $grid
* @return Integer
*/
function minPathSum($grid) {
$m = count($grid);
$n = count($grid[0]);
if ($m <= 0 || $n <= 0) return 0;
$dp = [];
$dp[0][0] = $grid[0][0];
for ($i = 1; $i < $m; $i++) {
$dp[$i][0] = $dp[$i - 1][0] + $grid[$i][0];
}
for ($j = 0; $j < $n; $j++) {
$dp[0][$j] = $dp[0][$j - 1] + $grid[0][$j];
}
for ($i = 1; $i < $m; $i++) {
for ($j = 1; $j < $n; $j++) {
$dp[$i][$j] = min($dp[$i - 1][$j], $dp[$i][$j - 1]) + $grid[$i][$j];
}
}
return $dp[$m - 1][$n - 1];
}
}