Skip to content

Commit 440e80e

Browse files
committed
dungeon_game
1 parent 3397bd5 commit 440e80e

File tree

2 files changed

+44
-0
lines changed

2 files changed

+44
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -150,6 +150,7 @@ Golang solution for leetcode. For each problem, there is a simple *_test.go to t
150150
#### [171. Excel Sheet Column Number](https://github.com/hitzzc/go-leetcode/tree/master/excel_sheet_column_number)
151151
#### [172. Factorial Trailing Zeroes](https://github.com/hitzzc/go-leetcode/tree/master/factorial_trailing_zeroes)
152152
#### [173. Binary Search Tree Iterator](https://github.com/hitzzc/go-leetcode/tree/master/binary_search_tree_iterator)
153+
#### [174. Dungeon Game](https://github.com/hitzzc/go-leetcode/tree/master/dungeon_game)
153154

154155

155156

dungeon_game/dungeon_game.go

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
package dungeon_game
2+
3+
func calculateMinimumHP(dungeon [][]int) int {
4+
if len(dungeon) == 0 || len(dungeon[0]) == 0 {
5+
return 0
6+
}
7+
matrix := make([][]int, len(dungeon))
8+
for i := range matrix {
9+
matrix[i] = make([]int, len(dungeon[0]))
10+
}
11+
rows := len(dungeon) - 1
12+
cols := len(dungeon[0]) - 1
13+
matrix[rows][cols] = dungeon[rows][cols]
14+
for i := rows - 1; i >= 0; i-- {
15+
matrix[i][cols] = min(dungeon[i][cols], matrix[i+1][cols]+dungeon[i][cols])
16+
}
17+
for j := cols - 1; j >= 0; j-- {
18+
matrix[rows][j] = min(dungeon[rows][j], matrix[rows][j+1]+dungeon[rows][j])
19+
}
20+
for i := rows - 1; i >= 0; i-- {
21+
for j := cols - 1; j >= 0; j-- {
22+
matrix[i][j] = min(dungeon[i][j], dungeon[i][j]+max(matrix[i+1][j], matrix[i][j+1]))
23+
}
24+
}
25+
if matrix[0][0] >= 0 {
26+
return 1
27+
}
28+
return 1 - 1*matrix[0][0]
29+
}
30+
31+
func max(i, j int) int {
32+
if i > j {
33+
return i
34+
}
35+
return j
36+
}
37+
38+
func min(i, j int) int {
39+
if i < j {
40+
return i
41+
}
42+
return j
43+
}

0 commit comments

Comments
 (0)