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

[LeetCode]174 Dungeon Game

时间:2015-01-14 18:17:17      阅读:140      评论:0      收藏:0      [点我收藏+]

标签:leetcode

https://oj.leetcode.com/problems/dungeon-game/

public class Solution {
    public int calculateMinimumHP(int[][] map)
    {
        // DP
        // Define a 2D M*N array blood.
        // blood[i][j] means the min blood when arrive this point.
        // So, the last point, blood[m - 1][n - 1] = 1
        //
        // blood[i][j] = max(1, // At least 1
        //                   min( blood[i][j + 1] - map[i][j + 1] , // go right
        //                        blood[i + 1][j] - map[i + 1][j] )) // go up
        // 
        //
        
        if (map == null)
            return 0;   // Invalid
        
        int m = map.length;
        int n = map[0].length;
        
        int[][] blood = new int[m][n];
        blood[m - 1][n - 1] = 1;
        for (int i = m - 1 ; i >= 0 ; i --)
        {
            for (int j = n - 1 ; j >= 0 ; j --)
            {
                if (i == m - 1 && j == n - 1)
                    continue;
                    
                int right = j + 1 < n ? blood[i][j + 1] - map[i][j + 1] : Integer.MAX_VALUE;
                int up = i + 1 < m ? blood[i + 1][j] - map[i + 1][j] : Integer.MAX_VALUE;
                blood[i][j] = Math.max(1, Math.min(right, up));
            }
        }
        
        return Math.max(1, blood[0][0] - map[0][0]);
    }
}


[LeetCode]174 Dungeon Game

标签:leetcode

原文地址:http://7371901.blog.51cto.com/7361901/1603925

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