LeetCode 174 Dungeon Game

经典的动态规划问题,每次保证血量不低于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;

}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值