Dungeon Game | Dynamic programming | Leetcode

Sdílet
Vložit
  • čas přidán 20. 06. 2020
  • This video explains a very important programming interview problem which is the dungeon game from leetcode #174.In this game, we are given a matrix of size N * M. Princess is present in the last cell (N,M) and the knight who will save her will start at (0,0).Each cell of the matrix is room of dungeon.Each of the room can be occupied by a demon or a magic orb.Knight looses an equal amount of health to fight demon and gains equal amount of health from a magical orb.As soon as the health of the knight reaches 0,he dies.We need to find the minimum health with which the knight should start such that there is atleast one possible path from the cell (0,0) to cell (N,N), so that the knight saves the princess.This is a variant of Minimum cost path problem.This can be solved using binary search and also using recursion.The best method to solve this is by using dynamic programming.I have explained the intuition for dynamic programming solution and have also explained the algorithm using proper examples.I have also shown the code walk through of the bottom-up dynamic programming at the end of the video.CODE LINK is present below as usual. If you find any difficulty or have any query then do COMMENT below. PLEASE help our channel by SUBSCRIBING and LIKE our video if you found it helpful...CYA :)
    =================================================================
    INSTAGRAM: / surya.pratap.k
    LinkedIn: / surya-pratap-kahar-47b...
    =================================================================
    CODE LINK: gist.github.com/SuryaPratapK/...
    USEFUL PROBLEM:-
    Minimum cost path: • Minimum path sum | Min...

Komentáře • 121

  • @sudhanshukumar1558
    @sudhanshukumar1558 Před 4 lety +10

    I started with 0,0 position
    here's my code for the recursion part, its in python.
    Some explanation dp is None initialised matrix, r=0.c=0 for first call to solve.
    def solve(self, dungeon, r, c, dp):
    # if we off the limits of the dungeon
    if r >= len(dungeon) or c >= len(dungeon[0]):
    return float('inf')
    # if we reach the queen
    if r == len(dungeon)-1 and c == len(dungeon[0])-1:
    dp[r][c] = 0 if dungeon[r][c] > 0 else abs(dungeon[r][c])
    return dp[r][c]

    # cache the value of right and down
    if not dp[r+1][c]:
    dp[r+1][c] = self.solve(dungeon, r+1, c, dp)
    if not dp[r][c+1]:
    dp[r][c+1] = self.solve(dungeon, r, c+1, dp)

    curr = dungeon[r][c]
    mini = min(dp[r+1][c], dp[r][c+1])
    if curr > 0:
    if curr >= mini:
    a=0
    else:
    a=mini-curr
    else:
    a = abs(curr)+mini
    dp[r][c] = a
    return dp[r][c]
    Be sure to add +1 to the returned value of the main call

  • @newcharm
    @newcharm Před 4 lety +30

    Trick to set positive numbers to zero was impossible for me to think, and not very easy to understand for me. But you have explained in a very clear and detailed way(your usual way). Please keep continue posting these videos.

    • @techdose4u
      @techdose4u  Před 4 lety +3

      Keep supporting and i will keep posting useful content :)

  • @allwell8570
    @allwell8570 Před 2 lety +7

    That logic of taking 0 instead of cumulative sum was just awesome🔥🔥

  • @priyanshuchaturvedi3706
    @priyanshuchaturvedi3706 Před 2 měsíci

    You always give the best and simple explanation whatever be the level of question.....Thankyou soo much

  • @DeepakGupta-te1tk
    @DeepakGupta-te1tk Před 3 lety +5

    It's not possible to build the table from top left to bottom down.
    This is because, in order to compute dp[i][j], you will need to make sure of two things:
    your dp[i][j]+dungeon[i][j] should be >0
    your dp[i][j]+dungeon[i][j] should be large enough, so that it will be sufficient to cover the minimum requirement on dp for the next step, be it right or down (take whichever requires smaller DP).
    So you see, because of the second requirement, your calculation of dp[i][j] will depend on later steps that you could take. This is why you have to know these later steps ahead of time, thus calculating from the bottom right.
    reference from leetcode 174 comment section.
    leetcode.com/problems/dungeon-game/discuss/52784/Who-can-explain-why-u201cfrom-the-bottom-right-corner-to-left-top.u201d

  • @ShubhamMahawar_Dancer_Actor

    Your SOLUTION is just like a HEAD SHOT to the PROBLEM,eliminated the problem in one way..GREAT MAN,..

  • @hemanthreddy8933
    @hemanthreddy8933 Před 4 lety +6

    I tried starting from 0,0 following the same approach of min-cost path and finally returning abs(dp[m-1][n-1)+1). Could you please explain why it is failing and what things to change in that method?

  • @qR7pK9sJ2t
    @qR7pK9sJ2t Před 3 lety +2

    Your efforts to make us understand this problem are commendable . Your an excellent teacher . Keep making videos . Cause their are a few extraordinary people like @myCodeSchool . They give us false hopes . Please never ever stop making videos .

  • @thunderbolt8632
    @thunderbolt8632 Před 4 lety +2

    Hello Sir,I have a doubt regarding one problem,I'm not sure if that can be done by DP.
    The question is similar to minimum cost path but instead of going from (0,0) to(n,n),we can go from any point of first column to any point of last column ((x,0)->(y,n))!Allowed moves are:up,down,right
    can u please suggest how can I approach this problem?

  • @dovyraj1272
    @dovyraj1272 Před 4 lety +1

    sir can we take dp[n][n][3] to store the current best, the best and heath need in a single box??

  • @goldymalav790
    @goldymalav790 Před 3 lety +2

    Can we solve this problem using top-down approach instead of bottom-approach?

  • @MahirHasancse21
    @MahirHasancse21 Před 4 lety +1

    Why do you start from row-1, col-1? Is it possible do the bottom up from 0,0 cell? If yes, can you tell me how it is possible. I tried from 0,0 cell but I can't.

  • @dekail4835
    @dekail4835 Před 3 lety +1

    I want to know if the game allows 4 directions to move, how to solve that?

  • @mausami16mau
    @mausami16mau Před 3 lety +1

    Your explanation made this problem very simple. Thank you :)

  • @pleasesirmorevideos4684

    sir as we know we can easily trace the path also which requires minimum health can we do it like after we trace that path and look for the minimum of all dp[i][j] belonging to that path?? that mnimum abs(min(dp[i][j] + 1)) will be the answer.... i am a bit tired to implement this but this won't be too hard. please reply

  • @biboswanroy6699
    @biboswanroy6699 Před 4 lety +1

    can this be soved with top down?

  • @AkshayKumar-xh2ob
    @AkshayKumar-xh2ob Před 3 lety +1

    Amazing work sir, giving so many videos for free on youtube is a major dent on online ed tech vultures

  • @meikandanathan2923
    @meikandanathan2923 Před 3 lety +2

    Excellent bro. You are a inspirational coder!!

  • @shobhitkumar6820
    @shobhitkumar6820 Před 4 lety +3

    sir what if i start start filling dp table from (0,0) and at the end return my abs(dp[n-1][m-1])+1. basically i want to say that dp[i][j] should contain minimum value to start from (0,0) and end at (i,j). I have tried this but my approach is not working.

  • @ginotamaca7827
    @ginotamaca7827 Před 4 lety +1

    Very nice explanation. Thank you! :)

  • @shivamgarg3890
    @shivamgarg3890 Před rokem +1

    what an explaination dude !

  • @shivangagrawal2923
    @shivangagrawal2923 Před 2 lety +1

    The way you solved this question is awesome

  • @sandeepkumawat4982
    @sandeepkumawat4982 Před 4 lety +1

    Woohhhoo That is just amazing ...Great

  • @akashverma270
    @akashverma270 Před 3 lety

    Brilliant Explanation

  • @yjj410
    @yjj410 Před 4 lety +3

    I did it first with DFS and Heap. I got time around 250 ms (python3) and there were many solutions for time around 70-80 ms. So I peeked into one and saw dp table. Then solved with DP and got good time. DP solution was easy to code once I solved it in notebook. First solution was quite long (I wrote Heap class, didnt use lib)

    • @thunderbolt8632
      @thunderbolt8632 Před 4 lety +1

      I was too thinking about solving it by heap but at the end did with DP

    • @techdose4u
      @techdose4u  Před 4 lety +3

      Nice :) I started with DP itself. Knew it was min cost path sum 😅

  • @AmitSingh-ut4wt
    @AmitSingh-ut4wt Před 4 lety +1

    Sir, I have one doubt regarding dp
    I searched on the internet I got one answer which says there is two way to perform dp one is memoization and other is tabulation. I saw many videos of dp questions where people solve it using tabulation and call it dp. In the memoization, we perform recursion and then try to store the value of the repeating structure in a ds so this is also called dp or not?

    • @techdose4u
      @techdose4u  Před 4 lety +2

      Yes both are dp. In the recursion method as well we use table to store repeating subproblems. So in both case we are using table and hence both can be called dp.

    • @AmitSingh-ut4wt
      @AmitSingh-ut4wt Před 4 lety

      @@techdose4u Thank you sir👍

  • @ashishg656
    @ashishg656 Před 4 lety +1

    Thanks, awesome explanation :)

  • @karansagar7870
    @karansagar7870 Před 4 lety +2

    Was Waiting for today's upload

  • @samarthjain5015
    @samarthjain5015 Před 4 měsíci

    Can you do the exact same thing top-down?

  • @abhilakshsharma1275
    @abhilakshsharma1275 Před 4 lety +1

    Is your solution working for the given input "[[-3,5]]" ?

    • @techdose4u
      @techdose4u  Před 4 lety +2

      Yes. DP table will have 0 in place of 6 and -3 in place of -3. So energy required will be 4.

  • @farazanwar4624
    @farazanwar4624 Před 2 lety +1

    thanxx for the imp observation part . It was great help

  • @parthshah6343
    @parthshah6343 Před 4 lety +1

    Why can't it be done in top down approach? How can we know whether we should we start from last cell or the first?

    • @techdose4u
      @techdose4u  Před 4 lety

      This is due the criteria for filling 0 from wherever you can reach the princess. We can't change the position of princess while filling the DP table. Just give it a thought and you will get it.

  • @sudhanshukumar1558
    @sudhanshukumar1558 Před 4 lety +2

    I also used the same approach, but I started with 0,0 position instead of last position, great explanation 😃

    • @techdose4u
      @techdose4u  Před 4 lety +2

      Some people have confusion in TOP-DOWN approach. If you can share your CODE then it will help everyone :)

    • @MahirHasancse21
      @MahirHasancse21 Před 4 lety +1

      Sudhanshu Kumar Can you tell me your approach?

    • @sudhanshukumar1558
      @sudhanshukumar1558 Před 4 lety +3

      here's my code for the recursion part, its in python.
      Some explanation dp is None initialised matrix, r=0.c=0 for first call to solve.
      def solve(self, dungeon, r, c, dp):
      # if we off the limits of the dungeon
      if r >= len(dungeon) or c >= len(dungeon[0]):
      return float('inf')
      # if we reach the queen
      if r == len(dungeon)-1 and c == len(dungeon[0])-1:
      dp[r][c] = 0 if dungeon[r][c] > 0 else abs(dungeon[r][c])
      return dp[r][c]

      # cache the value of right and down
      if not dp[r+1][c]:
      dp[r+1][c] = self.solve(dungeon, r+1, c, dp)
      if not dp[r][c+1]:
      dp[r][c+1] = self.solve(dungeon, r, c+1, dp)

      curr = dungeon[r][c]
      mini = min(dp[r+1][c], dp[r][c+1])
      if curr > 0:
      if curr >= mini:
      a=0
      else:
      a=mini-curr
      else:
      a = abs(curr)+mini
      dp[r][c] = a
      return dp[r][c]
      Be sure to add +1 to the returned value

    • @sudhanshukumar1558
      @sudhanshukumar1558 Před 4 lety

      @@techdose4u added it in the comment

    • @sudhanshukumar1558
      @sudhanshukumar1558 Před 4 lety +1

      @@MahirHasancse21 added it in the comment

  • @yitingg7942
    @yitingg7942 Před 3 lety +1

    Great great explanation Surya! Thanks a lot. May I just ask why we can't fill the cell from left up to right bottom,, what is the intuition behind this?

    • @techdose4u
      @techdose4u  Před 3 lety +1

      I had explained that one of the community post. See the date of this video release and scroll down in my community post section of channel. You will find it. I had told you this on a video call. You remeber?

  • @atefnazi753
    @atefnazi753 Před 2 lety +1

    can I say this is just a problem of finding minimum positive sum for reaching to the bottom-right cell

  • @Mimnmasiansunko
    @Mimnmasiansunko Před 11 měsíci

    If confidence table is given what to do

  • @paragroy5359
    @paragroy5359 Před 2 lety +1

    Nice explanation your videos are really good...please keep on making such videos.

  • @mayankjain876
    @mayankjain876 Před 4 lety +4

    i'm waiting for the day when you will explain egg drop problem,and all set of question related to matrix chain multiplication approach

  • @AmitKumar-xr6cy
    @AmitKumar-xr6cy Před 2 lety +1

    this question was asked in Uber coding round

  • @anirudhkanojia8803
    @anirudhkanojia8803 Před 2 lety +1

    I was doing it with bfs and getting tle, thanks for the explanation

  • @sreejiths2735
    @sreejiths2735 Před 4 lety +1

    Excellent explanation

  • @arindam1249
    @arindam1249 Před rokem

    excellent

  • @piyushnaithani7689
    @piyushnaithani7689 Před 4 lety +1

    I love this challenge 😍

    • @techdose4u
      @techdose4u  Před 4 lety +4

      June challenge is putting up good questions.

  • @hapysethi1306
    @hapysethi1306 Před 3 lety +1

    I wish to understand the problem like you.

  • @AA-rg1mv
    @AA-rg1mv Před 4 lety

    Is there any top down approach of filling table sir?

  • @peaceandlov
    @peaceandlov Před 3 lety +2

    awesome sir.

  • @manojshah5438
    @manojshah5438 Před rokem

    i was just about there but i was trying top down

  • @DonTaldo
    @DonTaldo Před 3 lety +1

    Awesome

  • @jatinvarshney01
    @jatinvarshney01 Před 4 lety +1

    bamm! wow!

  • @hemanthn436
    @hemanthn436 Před 3 lety +1

    Bro do video on
    Matrix median

  • @DeepakGupta-sx8xr
    @DeepakGupta-sx8xr Před 2 lety

    wow!!!!!!!!!!!!!!!!!!!

  • @TheMksShow
    @TheMksShow Před 4 lety +1

    Sir i didnt understand Why you are taking maximum of right and down

    • @techdose4u
      @techdose4u  Před 4 lety +1

      Because you want to take the minimum the minimum energy route. More the negative energy required for a path, more will be the cost. So, we take max if two path values which will give us the path with minimum required energy. Maximum of two negative values will give the one more closer to 0.

  • @PhenomenalInitiations
    @PhenomenalInitiations Před 2 lety

    Initially you said answer was 11, at the end it is 7

  • @toofangaming6380
    @toofangaming6380 Před 2 lety

    best

  • @shaileshhegde9205
    @shaileshhegde9205 Před 3 lety +2

    It was so confusing reading the question on Leetcode, it says if the sum goes below 0, the knight dies and the value starts from negative

  • @rajatnagpure7445
    @rajatnagpure7445 Před 4 lety +1

    This person is Angle!

  • @frustated_fool
    @frustated_fool Před 3 lety

    Bro, binary search method is intuitive

  • @ardalaaruna6315
    @ardalaaruna6315 Před 3 lety +3

    The dungeon question is somewhat difficult to understand...

  • @hs2075
    @hs2075 Před 4 lety +1

    What would DFS implementation be like?

  • @piyushnaithani7689
    @piyushnaithani7689 Před 4 lety

    Your codeforces ID?

    • @techdose4u
      @techdose4u  Před 4 lety

      I never did CP so I don't have anything to share on it. Replied on your question in another thread.

  • @gaunikasrivastava7851
    @gaunikasrivastava7851 Před 2 lety

    It's very tough to understand

  • @amritanshusharma4767
    @amritanshusharma4767 Před 3 lety

    Hey is this recursive logic correct ??
    int helper(vector &A,int i,int j,int n,int m,int power,int ans){
    if(i>=n || j>=m){
    return INT_MAX;
    }
    if(i==n-1 && j==m-1){
    power=power+A[i][j];
    if(power

  • @asgard3118
    @asgard3118 Před měsícem

    What kind of logic is that?

  • @dolandtrump3655
    @dolandtrump3655 Před 3 lety +3

    Your code is too easy to understand and we can build a logic after understanding it, but the explanation is really bad in the video. Too long video and literally I skipped to the code and understood why it is working.

  • @abhishekprasad3256
    @abhishekprasad3256 Před 2 měsíci

    not clearly explained, looks like he is just reading out the words

  • @VISHALMISHRA-ff2ih
    @VISHALMISHRA-ff2ih Před rokem

    why this code of you is getting failed.
    int r=dungeon.size();
    int c=dungeon[0].size();
    if(r==1 && c==1 && dungeon[0][0]>0)return 1;
    vectordp(r,vector(c));
    for(int i=r-1;i>=0;i--){
    for(int j=c-1;j>=0;j--){
    if(i==r-1 && j==c-1){
    dp[i][j]=dungeon[i][j];
    }
    else if(i==r-1){
    dp[i][j]=min(0,dp[i][j+1]+dungeon[i][j]);
    }
    else if(j==c-1){
    dp[i][j]=min(0,dp[i+1][j]+dungeon[i][j]);
    }
    else{
    dp[i][j]=min(0,dungeon[i][j]+max(dp[i+1][j],dp[i][j+1]));
    }
    }
    }
    return abs(dp[0][0])+1;