leetcode-dungeon-game
2015-11-28 15:52
477 查看
https://leetcode.com/problems/dungeon-game/
这个题目本来想用的代码如下
就是使用一个DFS来确定当前的hp值能否到达目标地点
再求最小的hp值的时候是递增的 不断地增加hp值看能否到达目标地点
但是最后提交的时候超时了 时间复杂度太高了 这种方法
第二种方法我用dfs搜索了所有的能够到达的路径
用Min值记录在整个路径中产生的最大伤害
然后从所有路径中寻找伤害最小的
这个题目本来想用的代码如下
就是使用一个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; } };
相关文章推荐
- 41.Android aapt工具
- asp.net实现输出xml的方法
- 选择图片
- java加载文件路径问题
- Spring声明式事务管理(基于注解的方式)
- angular实现两个select选择框互相传值
- HTML文本去除标签
- 正则表达式
- Remove Duplicates from Sorted List
- CCBPM节点访问规则与绑定人员的联系
- CodeForces 598D Igor In the Museum 暴力
- SQL使用
- 模板的继承
- 1-3-12:计算球的体积
- Linux-Centos 安装mono与monodevelop跨平台开发工具
- nyoj 1184 为了肾六 【dp】
- iOS 数组去重
- 千万级PV网站架构
- 242. Valid Anagram
- CSDN《老友记》简记