leetcode-dungeon-game

https://leetcode.com/problems/dungeon-game/
这个题目本来想用的代码如下
就是使用一个DFS来确定当前的hp值能否到达目标地点
再求最小的hp值的时候是递增的 不断地增加hp值看能否到达目标地点
但是最后提交的时候超时了 时间复杂度太高了 这种方法

#include <iostream>
#include <vector>
using namespace std;
class Solution {
public:
    int calculateMinimumHP(vector<vector<int>>& dungeon)
    {
        int i = 1;
        while (1)
        {
            if (!findPath(dungeon, i,0,0))
            {
                i++;
            }
            else
            {
                break;
            }
        }
        return i;
    }
private:
    bool findPath(vector<vector<int>>& dungeon, int health,int x,int y)//看以health的健康值是否可以走过x,y点
    {
        int currenthealth;
        if (x <= dungeon.size() - 1 && y <= dungeon[0].size() - 1)
        {
            currenthealth = health + dungeon[x][y];//计算出在x y点的健康值
        }
        else
            return false;
        if (currenthealth > 0)
        {
            if (x == dungeon.size() - 1 && y == dungeon[0].size() - 1)//找到了princess
                return true;

                bool temp1,temp2;
                temp1=findPath(dungeon, currenthealth, x + 1, y);//向下走
                if (temp1)
                    return true;
                temp2=findPath(dungeon, currenthealth, x, y + 1);//向右走
                if (temp2)
                    return true;
                return false;

        }
        return false;

    }
};

第二种方法我用dfs搜索了所有的能够到达的路径
用Min值记录在整个路径中产生的最大伤害
然后从所有路径中寻找伤害最小的

#include <iostream>
#include <vector>
using namespace std;
class Solution {
private:
    vector<int> allmin;
    void findPath(vector<vector<int>>& dungeon, int min,int pathharm, int x, int y)
    {
        if (x <= dungeon.size() - 1 && y <= dungeon[0].size() - 1)
        {
            pathharm+=dungeon[x][y];
            if (min > pathharm)
                min = pathharm;
            if (x == dungeon.size() - 1 && y == dungeon.size() - 1)
                allmin.push_back(min);
            else
            {
                findPath(dungeon, min, pathharm, x + 1, y);
                findPath(dungeon, min, pathharm, x, y + 1);
            }
        }
    }

public:
    int calculateMinimumHP(vector<vector<int>>& dungeon)
    {
        int maxmin;
        findPath(dungeon, 1000, 0, 0, 0);
        maxmin = allmin[0];
        for (int i = 0; i < allmin.size(); i++)
        {
            if (allmin[i] > maxmin)
                maxmin = allmin[i];
        }
        if (maxmin <= 0)
            return 1 - maxmin;
        else
            return 0;

    }

};
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

hebastast

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值