leetcode-dungeon-game
来源:互联网 发布:淘宝买的牙齿矫正器 编辑:程序博客网 时间:2024/05/21 02:48
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
- [leetcode] Dungeon Game
- leetcode 174: Dungeon Game
- [leetcode 174] Dungeon Game
- [leetcode] Dungeon Game
- Leetcode Dungeon Game
- LeetCode Dungeon Game
- LeetCode: Dungeon Game
- [LeetCode] Dungeon Game
- [leetcode] Dungeon Game
- LeetCode Dungeon Game
- [LeetCode]Dungeon Game
- Leetcode OJ Dungeon Game
- Leetcode: Dungeon Game
- leetcode dungeon game
- [leetcode]Dungeon Game
- LeetCode(174) Dungeon Game
- LeetCode 174 Dungeon Game
- LeetCode - Dungeon Game
- Spring声明式事务管理(基于注解的方式)
- angular实现两个select选择框互相传值
- 41.Android aapt工具
- UIWebview 适配 计算webview高度
- java加载文件路径问题
- leetcode-dungeon-game
- 单例类的使用方法
- 浅谈C++多态性 http://blog.csdn.net/hackbuteer1/article/details/7475622
- nyoj 找球号(二)【位运算压缩,离散化处理】
- shuoj1900 小6爱夜跑
- Java heap space
- Windows下mysql忘记root密码的解决方法
- Eclipse(adb)连不上Android手机 解决方法
- 大话设计模式 读书笔记