经典的动态规划问题,每次保证血量不低于1,从结尾处开始从下往上遍历赋值。
class Solution {
public:
/**
* it is a typical DP problem
* in the problem of DungeonGame, the most important idea is that knight must have 1HP at least
* so when knight go to the aim dungeaon, his hp must be min(1 hp , 1-dungeon[n-1][m-1])
* when knight go to the last row of dungeon, he can going right only,so his hp must be max(1, dungeon[i][j+1]-dungeon[i][j])
* when knight go to the last column of dungeon, he can going down only, so his hp must be max(1, dungeon[i+1][j]-dungeon[i][j])
* when knight go to the middle area of dungeon,he have choice going down or going right,so he can choose the smaller cost
* each room has at least 1 hp before into the room
*/
int calculateMinimumHP(vector<vector<int> > &dungeon) {
if(dungeon.size()==0) return 0;
long row=dungeon.size();
long col=dungeon[0].size();
for(long i=row-1; i>=0; i--) {
for(long j=col-1; j>=0; j--) {
if(i==row-1 && j==col-1) dungeon[i][j]=max(1, 1-dungeon[i][j]);
else if(i==row-1) dungeon[i][j]=max(1, dungeon[i][j+1]-dungeon[i][j]);
else if(j==col-1) dungeon[i][j]=max(1, dungeon[i+1][j]-dungeon[i][j]);
else dungeon[i][j]=max(1, min(dungeon[i+1][j], dungeon[i][j+1])-dungeon[i][j]);
}
}
return dungeon[0][0];
}
};
int main(int argc, const char * argv[]) {
// insert code here...
vector<vector<int>> datas;
// vector<int> data;
// data.push_back(-2);
// data.push_back(-3);
// data.push_back(3);
// datas.push_back(data);
//
// vector<int> data2;
// data2.push_back(-5);
// data2.push_back(-10);
// data2.push_back(-15);
// datas.push_back(data2);
srand( (unsigned)time(NULL));
//cout << rand() % 100 - 50;
for(int i=0;i<10000;i++){
vector<int> data;
for(int j=0;j<100;j++){
data.push_back(rand() % 100 - 50);
}
datas.push_back(data);
}
for(int i=0;i<10;i++){
vector<int> data = datas[i];
for(int j=0;j<10;j++){
cout<<data[j]<<" ";
}
cout<<endl;
}
// vector<int> data3;
// data3.push_back(10);
// data3.push_back(30);
// data3.push_back(-5);
// datas.push_back(data3);
Solution solution;
cout<<solution.calculateMinimumHP(datas);
return 0;
}