LeetCode - Dungeon Game

本文探讨了LeetCode迷宫游戏问题,通过动态规划逆向计算骑士从公主处返回起点所需的最小初始生命值,提供了详细的算法思路及Java实现。

https://leetcode.com/problems/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.


Write a function to determine the knight's minimum initial health so that he is able to rescue the princess.

For example, given the dungeon below, the initial health of the knight must be at least 7 if he follows the optimal path RIGHT-> RIGHT -> DOWN -> DOWN.

-2 (K) -3 3
-5 -10 1
10 30 -5 (P)

Notes:

  • The knight's health has no upper bound.
  • Any room can contain threats or power-ups, even the first room the knight enters and the bottom-right room where the princess is imprisoned.
这道题一看就知道是DP题,但是一开始总想着要保持最大血量,然后就从左到右,从上到下做的,结果不对,因为保持最大的血量不一定会导致最小的初始血量。

后来又想,那直接在计算出每个格子能得到的最大血量后,回溯回第一格,回溯方式也是按照找最大血量的格往回走,结果也不对,理由跟上面一样。

后来看了别人的解法,才发现,可以直接从后往前走,dp[i][j]记录的是进入[i, j]格前,如果能够到目的地,需要的最小血量。

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

就是,当前格需要的血量是当前格提供的血量(可能是负数)减去下一格需要的血量,就是剩下的血量,如果剩下的血量大于等于0的话,那么进入当前格前只需要血量1就可以了,如果剩下的血量小于0的话,就需要提供这些血量。

注意,下一格一般有两个选项 (i, j+1) 和 (i+1, j),选择小的那个,当i=m-1或者j=n-1时就只有一个选项了。

最后dp[0][0]就是进入之前需要的最小血量。

public class Solution {
    public int calculateMinimumHP(int[][] dungeon) {
        if(dungeon.length == 0) return 0;
        int m = dungeon.length;
        int n = dungeon[0].length;
        int max = 1;
        int[][] dp = new int[m][n];
        int i=m-1, j=n-1;
        dp[m-1][n-1] = dungeon[m-1][n-1]>=0? 1: -dungeon[m-1][n-1]+1;
        
        for(i=m-1; i>=0; i--){
            for(j=n-1; j>=0; j--){
                if(i==(m-1) && j==(n-1)) continue;
                if(i==(m-1)){
                    int need = dungeon[i][j]-dp[i][j+1];
                    dp[i][j] = need>=0 ? 1 : -need;
                    continue;
                }
                if(j==(n-1)){
                    int need = dungeon[i][j]-dp[i+1][j];
                    dp[i][j] = need>=0 ? 1 : -need;
                    continue;
                }
                int need = dungeon[i][j] - Math.min(dp[i][j+1], dp[i+1][j]);
                dp[i][j] = need>=0 ? 1 : -need;
            }
        }
        return dp[0][0];
    }
}

DP如果求第一个位置的某些值,可以从后往前走,注意考虑到这种思维方式。

注意,这里可以直接用一维DP,或者直接在原来dungeon数组里面操作,就只需要O(n)或者O(1)时间复杂度了。

一维DP代码如下:

public class Solution {
    public int calculateMinimumHP(int[][] dungeon) {
        if(dungeon.length == 0) return 0;
        int m = dungeon.length;
        int n = dungeon[0].length;
        int max = 1;
        int[] dp = new int[n];
        int i=m-1, j=n-1;
        dp[n-1] = dungeon[m-1][n-1]>=0? 1: -dungeon[m-1][n-1]+1;
        
        for(i=m-1; i>=0; i--){
            for(j=n-1; j>=0; j--){
                if(i==(m-1) && j==(n-1)) continue;
                if(i==(m-1)){
                    int need = dungeon[i][j]-dp[j+1];
                    dp[j] = need>=0 ? 1 : -need;
                    continue;
                }
                if(j==(n-1)){
                    int need = dungeon[i][j]-dp[j];
                    dp[j] = need>=0 ? 1 : -need;
                    continue;
                }
                int need = dungeon[i][j] - Math.min(dp[j+1], dp[j]);
                dp[j] = need>=0 ? 1 : -need;
            }
        }
        return dp[0];
    }
}

这道题还有tag是binary search, 不过没想出来binary search的方法。。。这里有个binary search的代码,有空研究一下:

https://leetcode.com/discuss/25671/a-simple-c-solution-using-binary-search

增加C++代码,这里直接在dungeon上改的,可以定义C++数组,注意C++数组和JAVA定义语句是不一样的:

class Solution {
public:
    int calculateMinimumHP(vector<vector<int> > &dungeon) {
        int row = dungeon.size();   
        int col = dungeon[0].size();   //int dp[row][col]; <span style="font-family: 'small Monaco', Menlo, Consolas, 'Courier New', monospace; line-height: 17.142858505249px; white-space: pre; background-color: rgb(238, 238, 238);">memset(dp,</span><span class="number" style="box-sizing: border-box; color: rgb(0, 136, 0); font-family: 'small Monaco', Menlo, Consolas, 'Courier New', monospace; line-height: 17.142858505249px; white-space: pre; background-color: rgb(238, 238, 238);">0</span><span style="font-family: 'small Monaco', Menlo, Consolas, 'Courier New', monospace; line-height: 17.142858505249px; white-space: pre; background-color: rgb(238, 238, 238);">,</span><span class="keyword" style="box-sizing: border-box; font-weight: bold; font-family: 'small Monaco', Menlo, Consolas, 'Courier New', monospace; line-height: 17.142858505249px; white-space: pre; background-color: rgb(238, 238, 238);">sizeof</span><span style="font-family: 'small Monaco', Menlo, Consolas, 'Courier New', monospace; line-height: 17.142858505249px; white-space: pre; background-color: rgb(238, 238, 238);">(dp));</span>
        for(int i=row-1; i>=0; i--){
            for(int j=col-1; j>=0; j--){
                if(i==(row-1) && j==(col-1)) dungeon[i][j] = dungeon[i][j]<0 ? -dungeon[i][j]+1 : 1;
                else{
                    int need;
                    if(i==(row-1)) need = dungeon[i][j]-dungeon[i][j+1];
                    else if(j==(col-1)) need = dungeon[i][j] - dungeon[i+1][j];
                    else need = dungeon[i][j] -min(dungeon[i][j+1], dungeon[i+1][j]);
                    dungeon[i][j] = need<0? -need: 1;
                }
            }
        }
        return dungeon[0][0];  //return dp[0][0]
    }
};


<think>好的,我现在需要帮用户解决一个Node.js中的TypeError问题,错误信息是“TypeError: cb is nota function”。用户提供的错误堆栈显示这个问题发生在parseCookie函数中,具体是在调用cb的时候。首先,我得分析可能的原因。 首先,错误信息指出cb不是一个函数。这通常意味着在调用某个函数时,传入的回调参数不是函数类型。可能的情况包括: 1. **回调未正确传递**:可能在调用parseCookie时,没有正确传递回调函数,或者传递了错误的参数类型。 2.**函数定义参数不匹配**:parseCookie函数可能期望一个回调函数作为参数,但在调用时可能没有传入或者传入了其他类型的值。 3. **异步处理问题**:可能使用了错误的回调方式,比如应该使用函数的地方用了Promise或其他异步处理方式。 4. **第三方库版本问题**:可能使用的库版本过旧或存在bug,导致回调参数处理异常。 接下来,我需要根据用户提供的堆栈信息来定位具体的位置。错误发生在leetcode.js的parseCookie函数第542行,调用cb的地方。这可能是一个插件或模块中的函数,用户可能在使用VSCode的LeetCode插件时遇到了问题,尤其是在处理cookie登录时。 考虑到用户提到的环境是Node.js v22.17.0,可能存在兼容性问题。某些旧版本的库可能不兼容较新的Node.js版本,导致回调参数未被正确处理。 用户可能需要检查以下几点: -检查parseCookie函数的定义,确认其参数是否正确要求一个回调函数。 -查看调用parseCookie的地方是否正确传递了回调函数。 -确认第三方库(如vsc-leetcode-cli)是否支持当前Node.js版本,可能需要升级或降级版本。- 查看是否有相关的Issue或更新日志,可能其他用户也遇到了类似的问题。 可能的解决方案包括:1. 更新LeetCode插件到最新版本,修复可能存在的bug。2. 降级Node.js版本到更稳定的版本,比如LTS版本,以确保兼容性。 3. 如果问题由特定代码引起,检查代码中回调函数的使用是否正确。 4.清除缓存或重新安装插件,解决可能的配置错误。 此外,用户可能需要提供更多的上下文信息,比如他们正在执行的操作,或者相关的代码片段,以便更准确地定位问题。例如,是否在自定义代码中调用了parseCookie函数,或者这完全是由插件内部触发的错误。 总结来说,用户需要检查回调函数的传递和定义,确认第三方库的兼容性,并考虑环境配置是否合适。如果问题持续存在,建议查看插件的官方文档或提交Issue寻求帮助。</think>`TypeError: cb is not a function` 表示在调用 `parseCookie` 函数时,传递的 `cb` 参数 **不是函数类型**。以下是关键分析及解决方案: --- ### ❌ 错误原因 1. **回调参数类型错误** `parseCookie` 函数内部尝试调用 `cb(...)`,但传入的 `cb` 可能是 `null`、`undefined` 或其他非函数类型(如字符串、数字)。 2. **函数定义与调用不匹配** - 函数定义时要求传入回调函数: ```javascript function parseCookie(cookieStr, cb) { ... } ``` - 调用时却未传递有效回调: ```javascript parseCookie("key=value", "错误参数"); // 第二个参数不是函数 ``` 3. **第三方库兼容性问题** 根据路径 `vsc-leetcode-cli` 和 Node.js v22.17.0,可能是 **LeetCode 插件与最新 Node.js 版本不兼容**,导致内部回调参数传递异常。 --- ### ✅ 解决方案 1. **检查调用方代码** 定位 `parseCookie` 的调用位置(如 `leetcode.js` 第 565 行),确保传递正确的回调函数: ```javascript parseCookie("key=value", (err, result) => { if (err) throw err; console.log(result); }); ``` 2. **更新插件版本** `vsc-leetcode-cli` 可能存在旧版 bug,尝试更新插件: ```bash npm install -g vsc-leetcode-cli@latest ``` 或重新安装 VSCode LeetCode 插件。 3. **降级 Node.js 版本** Node.js v22.x 是较新版本,可能存在兼容性问题。建议切换到 **LTS 版本(如 v18.x 或 v20.x)**: - 使用 [nvm](https://github.com/nvm-sh/nvm) 管理多版本 Node.js。 4. **临时修复(绕过错误)** 在调用 `parseCookie` 前增加类型检查: ```javascript if (typeof cb === 'function') { cb(null, parsedCookie); } else { console.error("回调参数必须为函数"); } ``` --- ### 🧪 验证步骤 1. 确认 Node.js 版本: ```bash node -v # 推荐使用 v18.x 或 v20.x ``` 2. 检查插件依赖: 进入插件目录并更新依赖: ```bash cd ~/.vscode-huawei/extensions/leetcode.vscode-leetcode-0.18.1 npm install ``` --- ### ❓ 常见相关问题
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值