"Leetcode" Dungeon Game

Source: Internet
Author: User

Dungeon Game

The Demons had captured the Princess (P) and imprisoned her in the Bottom-right corner of a dungeon. The dungeon consists of M x N Rooms laid out in a 2D grid. Our Valiant Knight (K) is initially positioned in the top-left, and must fight his, through the dungeon to rescue The princess.

The knight has an initial health point represented by a positive integer. Drops to 0 or below, he dies immediately.

Some of the rooms is guarded by demons, so the knight loses health (negative integers) upon entering these rooms ; Other rooms is either empty (0 ' s) or contain magic orbs that increase the knight ' s Health (positive int Egers).

In order to reach the princess as quickly as possible, the Knight decides to move only rightward or downward in each step.

Write a function to determine the knight's minimum initial health so that he's able to rescue the princess.

For example, given the dungeon below, the initial health of the knight must is at least 7 if he follows the optimal path c0/>.

-2 (K) -3 3
-5 -10 1
10 30 -5 (P)

Notes:

    • The Knight ' s Health has no upper bound.
    • Any hostel can contain threats or power-ups, even the first, the knight enters and the Bottom-right, where the Princ ESS is imprisoned.

Credits:
Special thanks to @stellari for adding this problem and creating all test cases.

classSolution { Public:    intCALCULATEMINIMUMHP (vector<vector<int> > &Dungeon) {        intm =dungeon.size (); intn = dungeon[0].size (); Vector<vector<int> > Ret (M, vector<int>(n)); Ret[m-1][n-1] = max (1,1-dungeon[m-1][n-1]);  for(inti = m2; I >=0; I--) Ret[i][n-1] = max (1, ret[i+1][n-1]-dungeon[i][n-1]);  for(intj = N2; J >=0; J--) Ret[m-1][J] = max (1, ret[m-1][j+1]-dungeon[m-1][j]);  for(inti = m2; I >=0; I--)        {             for(intj = N2; J >=0; J--) {Ret[i][j]= Max (1, Min (ret[i+1][J]-DUNGEON[I][J], ret[i][j+1]-dungeon[i][j])); }        }        returnret[0][0]; }};

"Leetcode" Dungeon Game

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.