码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode – Refresh – Dungeon Game

时间:2015-03-19 08:51:07      阅读:138      评论:0      收藏:0      [点我收藏+]

标签:

Since it need the min value of initial health, this dp tracks from the back to the start.

The trick is either this knight has 1 health or base on next step‘s minimum health minus current dungeon value. Why is minus?

Because when you count the health is health + dungeon[i][j].

 

 1 class Solution {
 2 public:
 3     int calculateMinimumHP(vector<vector<int> > &dungeon) {
 4         if (dungeon.size() == 0) return 1;
 5         int n = dungeon.size(), m = dungeon[0].size();
 6         vector<vector<int> > dp(n, vector<int> (m, 0));
 7         dp[n-1][m-1] = max(1, 1 - dungeon[n-1][m-1]);
 8         for (int i = n-2; i >= 0; i--) {
 9             dp[i][m-1] = max(1, dp[i+1][m-1] - dungeon[i][m-1]);
10         }
11         for (int i = m-2; i >= 0; i--) {
12             dp[n-1][i] = max(1, dp[n-1][i+1] - dungeon[n-1][i]);
13         }
14         for (int i = n-2; i >= 0; i--) {
15             for (int j = m-2; j >= 0; j--) {
16                 dp[i][j] = max(1, min(dp[i][j+1], dp[i+1][j]) - dungeon[i][j]);
17             }
18         }
19         return dp[0][0];
20     }
21 };

 

LeetCode – Refresh – Dungeon Game

标签:

原文地址:http://www.cnblogs.com/shuashuashua/p/4349403.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!