Skip to content

Commit

Permalink
Dungeon game (#214)
Browse files Browse the repository at this point in the history
* add dungeon game

* impl dungeon game

* update small
  • Loading branch information
SKTT1Ryze authored Mar 20, 2024
1 parent 172cded commit d69c519
Show file tree
Hide file tree
Showing 2 changed files with 61 additions and 0 deletions.
55 changes: 55 additions & 0 deletions leetcode-cc/DungeonGame.hpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
#include <algorithm>
#include <cmath>

#include "TestHelper.h"
#include "problem.h"
#include "solution.h"

using namespace std;

IMPLEMENT_PROBLEM_CLASS(PDungeonGame, 174, DIFFI_HARD, TOPIC_ALGORITHMS,
"Dungeon Game",
"Return the knight's minimum initial health so that he "
"can rescue the princess.",
{"DP"});

class SDungeonGame : public ISolution {
public:
size_t problemId() const override { return 174; }
string name() const override {
return ("Solution for " + string("Dungeon Game"));
}
string location() const override { return __FILE_NAME__; }
int test() const override {
return testHelper<vector<vector<int>>, int>(
{{{-2, -3, 3}, {-5, -10, 1}, {10, 30, -5}}, {{0}}}, {7, 1},
[this](auto input) { return this->calculateMinimumHP(input); });
};
int benchmark() const override { return 0; }

private:
int calculateMinimumHP(vector<vector<int>>& dungeon) const {
int m = dungeon.size();
int n = dungeon[0].size();

vector<vector<int>> dp(m, vector(n, 0));

dp[m - 1][n - 1] = max(1, 1 - dungeon[m - 1][n - 1]);

for (int i = n - 2; i >= 0; i--)
dp[m - 1][i] = max(1, dp[m - 1][i + 1] - dungeon[m - 1][i]);

for (int i = m - 2; i >= 0; i--)
dp[i][n - 1] = max(1, dp[i + 1][n - 1] - dungeon[i][n - 1]);

for (int i = m - 2; i >= 0; i--) {
for (int j = n - 2; j >= 0; j--) {
int down = max(1, dp[i + 1][j] - dungeon[i][j]);
int right = max(1, dp[i][j + 1] - dungeon[i][j]);
dp[i][j] = min(down, right);
}
}

return dp[0][0];
}
};
6 changes: 6 additions & 0 deletions runtime-cc/src/registration.cc
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@
#include "../leetcode-cc/DeterIfStringHalvesAreAlike.hpp"
#include "../leetcode-cc/DistinctSubsequences.hpp"
#include "../leetcode-cc/DivideTwoIntegers.hpp"
#include "../leetcode-cc/DungeonGame.hpp"
#include "../leetcode-cc/EvaluateReversePolishNotation.hpp"
#include "../leetcode-cc/ExcelSheetColNum.hpp"
#include "../leetcode-cc/ExcelSheetColTitle.hpp"
Expand Down Expand Up @@ -813,5 +814,10 @@ const int registerAll(std::shared_ptr<Container> handle) {
handle->registerSolution(
[]() -> ArcSolution { return std::make_shared<SNumOfIslands>(); });

handle->registerProblem(
[]() -> ArcProblem { return std::make_shared<PDungeonGame>(); });
handle->registerSolution(
[]() -> ArcSolution { return std::make_shared<SDungeonGame>(); });

return 0;
}

0 comments on commit d69c519

Please sign in to comment.