题目链接

题目大意:从左上角到右下角,每一个格子都有各自的权值,如果权值为负,则当到达时,要失血;如果权值为正,则当到达时,要加血。当到达某个格子时,当前血量<=0,则死亡,到达不了右下角,所以此时要计算从左上角到右下角,初始应该最少携带多少血(即经过所有路径后所计算出的值),才不会死亡,能正常到达右下角。

法一:dfs,模板深搜,果断超时。要注意:更新点不是整条路径的和(与64题比较)的最小值,而是整条路径中所达到的最大的失血量,如果最大失血量>=0,则本身只需要携带1个血即可;否则本身携带的血应该=abs(最大失血量)+1。代码如下:

 1     public int calculatedMinimumHP(int[][] dungeon) {
 2         boolean vis[][] = new boolean[dungeon.length][dungeon[0].length];
 3         int f[][] = {{1, 0}, {0, 1}};
 4         vis[0][0] = false;
 5         return dfs(dungeon, 0, 0, dungeon[0][0], Integer.MAX_VALUE, dungeon[0][0], vis, f);
 6     }
 7     public int dfs(int[][] dungeon, int x, int y, int sum, int res, int blood, boolean vis[][], int f[][]) {
 8         if(x == dungeon.length - 1 && y == dungeon[0].length - 1) {
 9             //递归结束点是每条线路的过程中的最大失血量
10             if(blood < 0) {//如果失血量为负数,则是绝对值+1
11                 if(Math.abs(blood) < res) {
12                     res = Math.abs(blood) + 1;
13                  }
14             }
15             else {//如果失血量>=0,则是1,因为当失血量为0时,也会死亡
16                 res = 1;
17             }
18             return res;
19         }
20         for(int i = 0; i < 2; i++) {
21             int cnt_x = x + f[i][0];
22             int cnt_y = y + f[i][1];
23             if(cnt_x < dungeon.length && cnt_y < dungeon[0].length && vis[cnt_x][cnt_y] == false) {
24                 vis[cnt_x][cnt_y] = true;
25                 res = dfs(dungeon, cnt_x, cnt_y, sum + dungeon[cnt_x][cnt_y], res, blood < (sum + dungeon[cnt_x][cnt_y]) ? blood : (sum + dungeon[cnt_x][cnt_y]), vis, f);
26                 vis[cnt_x][cnt_y] = false;
27             }
28         }
29         return res;
30     }
View Code

相关文章:

  • 2021-10-24
  • 2022-12-23
  • 2022-12-23
  • 2021-04-09
  • 2021-06-26
  • 2021-06-28
  • 2022-03-13
  • 2022-12-23
猜你喜欢
  • 2021-12-07
  • 2022-01-12
  • 2022-12-23
  • 2021-12-30
  • 2021-09-20
  • 2021-07-30
相关资源
相似解决方案