An interesting problem. The code is also short and clear.
The basic idea was to use a 2d array dp[i][j] to denote the minimum HP this is required before entering Dungeo N[I][J]. Since the knight needs to being alive after entering the Bottom-right cell of the dungeon, we'll update DP from Bo Ttom-right to Top-left. The updating formula is also simple:
DP[I][J] = max (1, min (dp[i][j + 1], Dp[i + 1][j])-dungeon[i][j]).
Taking the maximum with 1 guarantees, the HP of the knight never drops to or below 0. Since the knight only moves in and directions:rightwards or downwards, each cell (Dp[i][j]) was only related to I TS Right (d[i][j + 1]) and down (dp[i + 1][j]) neighbors.
The following code barely translates the above idea, while adding dummy rows and columns for initializations.
1 classSolution {2 Public:3 intCALCULATEMINIMUMHP (vector<vector<int>>&Dungeon) {4 intm = Dungeon.size (), n = dungeon[0].size ();5vector<vector<int>> DP (M +1, vector<int> (n +1, Int_max));6Dp[m][n-1] = dp[m-1][n] =1;//initialization7 for(inti = m-1; I >=0; i--)8 for(intj = N-1; J >=0; j--)9DP[I][J] = max (min (dp[i][j +1], Dp[i +1][J])-dungeon[i][j],1);Ten returndp[0][0]; One } A};
Of course, the 2d array can be simplified to a 1d array if we ' ve been clear of what DP is updated (in the above CO DE, dp is updated row by row from the bottom one to the top one and the all row it is updated from right to left) . The 1d version is as follows.
1 classSolution {2 Public:3 intCALCULATEMINIMUMHP (vector<vector<int>>&Dungeon) {4 intm = Dungeon.size (), n = dungeon[0].size ();5vector<int> dp (n +1, Int_max); Dp[n-1] =1;//initialization6 for(inti = m-1; I >=0; i--)7 for(intj = N-1; J >=0; j--)8DP[J] = max (min (dp[j], dp[j +1])-DUNGEON[I][J],1);9 returndp[0];Ten } One};
Well, if you get confused, try-to-run the 2d code on the example in the problem statement and record the values of dp< /c6> near the corresponding values of dungeon using different colors, as the following picture. After this, you'll be clear, even of the 1d code:-)
[Leetcode] Dungeon Game