Java for LeetCode 174 Dungeon Game

The demons had captured the princess (P) and imprisoned her in the bottom-right corner of a dungeon. The dungeon consists of M x N rooms laid out in a 2D grid. Our valiant knight (K) was initially positioned in the top-left room and must fight his way through the dungeon to rescue the princess.

The knight has an initial health point represented by a positive integer. If at any point his health point drops to 0 or below, he dies immediately.

Some of the rooms are guarded by demons, so the knight loses health (negative integers) upon entering these rooms; other rooms are either empty (0's) or contain magic orbs that increase the knight's health (positive integers).

In order to reach the princess as quickly as possible, the knight decides to move only rightward or downward in each step.

解题思路:

dp问题,有两种思路:

思路一:dp[i][j]表示从起点到dungeon[i][j]所需的最小血量,但是这种思路递推方程非常不好写

思路二:dp[i][j]表示从dungeon[i][j]到终点所需的最小血量,使用一维数组即可,递推方程

dp[j] = dungeon[i][j] >= Math.min(dp[j + 1], dp[j]) - 1 ? 1: Math.min(dp[j + 1], dp[j]) - dungeon[i][j]

当然,也可以直接用dungeon[i][j]数组替代dp[]数组,JAVA实现如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
public int calculateMinimumHP(int[][] dungeon) {
    int[] dp = new int[dungeon[0].length];
    dp[dungeon[0].length - 1] = dungeon[dungeon.length - 1][dungeon[0].length - 1] >= 0 ? 1
            : 1 - dungeon[dungeon.length - 1][dungeon[0].length - 1];
    for (int i = dungeon[0].length - 2; i >= 0; i--)
        dp[i] = dungeon[dungeon.length - 1][i] >= dp[i + 1] - 1 ? 1
                : dp[i + 1] - dungeon[dungeon.length - 1][i];
    for (int i = dungeon.length - 2; i >= 0; i--) {
        dp[dungeon[0].length - 1] = dungeon[i][dungeon[0].length - 1] >= dp[dungeon[0].length - 1] - 1 ? 1
                : dp[dungeon[0].length - 1]
                        - dungeon[i][dungeon[0].length - 1];
        for (int j = dungeon[0].length - 2; j >= 0; j--)
            dp[j] = dungeon[i][j] >= Math.min(dp[j + 1], dp[j]) - 1 ? 1
                    : Math.min(dp[j + 1], dp[j]) - dungeon[i][j];
    }
    return dp[0];
}

 

posted @   TonyLuis  阅读(220)  评论(0编辑  收藏  举报
编辑推荐:
· Linux glibc自带哈希表的用例及性能测试
· 深入理解 Mybatis 分库分表执行原理
· 如何打造一个高并发系统?
· .NET Core GC压缩(compact_phase)底层原理浅谈
· 现代计算机视觉入门之:什么是图片特征编码
阅读排行:
· 手把手教你在本地部署DeepSeek R1,搭建web-ui ,建议收藏!
· Spring AI + Ollama 实现 deepseek-r1 的API服务和调用
· 数据库服务器 SQL Server 版本升级公告
· 程序员常用高效实用工具推荐,办公效率提升利器!
· C#/.NET/.NET Core技术前沿周刊 | 第 23 期(2025年1.20-1.26)
点击右上角即可分享
微信分享提示