Skip to content

Commit 7f570e8

Browse files
committed
Add solution 174.
1 parent c0df00f commit 7f570e8

File tree

1 file changed

+33
-0
lines changed

1 file changed

+33
-0
lines changed
Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
class Solution {
2+
3+
private $dp;
4+
private $visited;
5+
6+
/**
7+
* @param Integer[][] $dungeon
8+
* @return Integer
9+
*/
10+
function calculateMinimumHP(&$dungeon) {
11+
$dp = array_fill(0, count($dungeon), array_fill(0, count($dungeon[0]), 0));
12+
$visited = array_fill(0, count($dungeon), array_fill(0, count($dungeon[0]), false));
13+
$val = self::solve($dungeon, 0, 0);
14+
return $val >= 1 ? 1 : 1-$val;
15+
}
16+
17+
function solve(&$dungeon, $i, $j) {
18+
if($i == count($dungeon)-1 && $j == count($dungeon[0])-1) return $dungeon[$i][$j];
19+
if($i == count($dungeon)) return -2147483647;
20+
if($j == count($dungeon[0])) return -2147483647;
21+
22+
if($visited[$i][$j]) {
23+
return $dp[$i][$j];
24+
}
25+
26+
$val = min($dungeon[$i][$j] + max(self::solve($dungeon, $i+1, $j), self::solve($dungeon, $i, $j+1)), $dungeon[$i][$j]);
27+
28+
$dp[$i][$j] = $val;
29+
$visited[$i][$j] = true;
30+
31+
return $val;
32+
}
33+
}

0 commit comments

Comments
 (0)