0

I just completed problem #174 - Dungeon Game https://leetcode.com/problems/dungeon-game/

My code runs perfectly and is correct when testing it in Leetcode's own "Run Code Result" box with the EXACT same testing parameters, but it fails in the submissions box. Here is my code:

class Solution:
    min_hp = 0

    def calculateMinimumHP(self, dungeon, pos_x = 0, pos_y = 0, init_hp = 1, damage = 0) -> int:
        damage += dungeon[pos_y][pos_x]
        
        if init_hp + damage <= 0:
            init_hp += 1
            return Solution.calculateMinimumHP(self, dungeon, pos_x, pos_y, init_hp, damage - dungeon[pos_y][pos_x])
        elif init_hp > Solution.min_hp and Solution.min_hp != 0:
            return
        elif pos_x + 1 == len(dungeon) and pos_y + 1 == len(dungeon[0]):
            Solution.min_hp = init_hp
            return Solution.min_hp
    
        if pos_x + 1 < len(dungeon):
            Solution.calculateMinimumHP(self, dungeon, pos_x+1, pos_y, init_hp, damage)
        if pos_y + 1 < len(dungeon[0]):
            Solution.calculateMinimumHP(self, dungeon, pos_x, pos_y+1, init_hp, damage)
    
        return Solution.min_hp

Any ideas would be helpful!

0

1 Answer 1

1

When you "submit", LeetCode tests your solution with multiple test cases. It does create a new Solution instance for each test case, but that's all the "freshness" you get. So your problem is that your Solution.min_hp doesn't get reset to zero between test cases.

A quick fix would be to reset it yourself when a new instance is created:

class Solution:
    def __init__(self):
        Solution.min_hp = 0

    def calculateMinimumHP(self, dungeon, pos_x = 0, pos_y = 0, init_hp = 1, damage = 0) -> int:
        ....

It then fails on a later test case, as you appear to have another bug.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you! I'll fix the bug on my own, but this was driving my crazy.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.