您的位置:首页 > 其它

leetcode-dungeon-game

2015-11-28 15:52 477 查看
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;

}

};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: