1. Brute Force — Recursive Backtracking
Intuition
At each cell (r, c), recursively compute the minimum health needed to finish the game by taking the right path and the down path.
Algorithm
- Initialize required state variables and allocate data structures for Brute Force — Recursive Backtracking.
- Iterate through the input array and apply the core algorithmic condition.
- Update boundaries, frequencies, or pointers in accordance with the invariant.
- Return the computed result or transformed array.
Recursive Backtracking Trace
2 of 2 questions left todayPrincess room at (2,2) with val = -5
Princess room at (2,2) with val = -5. Knight must have >= 1 health after room: health - 5 >= 1.
#include <iostream>#include <vector>#include <algorithm>#include <climits> using namespace std; class Solution {private: int solve(const vector<vector<int>>& dungeon, int r, int c, int m, int n) { if (r == m - 1 && c == n - 1) { return max(1, 1 - dungeon[r][c]); } int right = (c + 1 < n) ? solve(dungeon, r, c + 1, m, n) : INT_MAX; int down = (r + 1 < m) ? solve(dungeon, r + 1, c, m, n) : INT_MAX; int minHealthNext = min(right, down); return max(1, minHealthNext - dungeon[r][c]); } public: int calculateMinimumHP(vector<vector<int>>& dungeon) { int m = dungeon.size(), n = dungeon[0].size(); return solve(dungeon, 0, 0, m, n); }}; int main() { Solution sol; vector<vector<int>> dungeon = {{-2, -3, 3}, {-5, -10, 1}, {10, 30, -5}}; cout << "Input: [[-2,-3,3],[-5,-10,1],[10,30,-5]]\n"; cout << "Brute Force Min HP: " << sol.calculateMinimumHP(dungeon) << "\n"; return 0;}Time & Space Complexity
- Time complexity:
O(N^2)— Time complexity for Brute Force — Recursive Backtracking. - Space complexity:
O(1)— Space complexity for Brute Force — Recursive Backtracking.
Why Brute Force Doesn't Scale:
For a 20x20 dungeon, 240 exceeds 1 trillion operations.
1D Dynamic Programming solves a 200x200 grid (40,000 cells) in under 1 millisecond using just 201 integers of memory.