Skip to content

Instantly share code, notes, and snippets.

@leearmee35
Last active August 22, 2016 04:50
Show Gist options
  • Save leearmee35/3b4087594b11fc706c63e0df3773f085 to your computer and use it in GitHub Desktop.
Save leearmee35/3b4087594b11fc706c63e0df3773f085 to your computer and use it in GitHub Desktop.
public class Solution {
public int calculateMinimumHP(int[][] dungeon) {
int m=dungeon.length;
int n=dungeon[0].length;
int dp[][] = new int[m][n];
dp[m-1][n-1] = Math.max(1-dungeon[m-1][n-1],1);
for(int i=n-2;i>=0;i--){
dp[m-1][i] = Math.max(dp[m-1][i+1]-dungeon[m-1][i],1);
}
for(int i=m-2;i>=0;i--){
dp[i][n-1] = Math.max(dp[i+1][n-1]-dungeon[i][n-1],1);
}
for(int i=m-2;i>=0;i--){
for(int j=n-2;j>=0;j--){
int toRight = Math.max(dp[i][j+1]-dungeon[i][j],1);
int toDown = Math.max(dp[i+1][j]-dungeon[i][j],1);
dp[i][j] = Math.min(toRight,toDown);
}
}
return dp[0][0];
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment