Home > OS >  My Leetcode solution works in "Run Code Result" box, but not in the "Submissions box&
My Leetcode solution works in "Run Code Result" box, but not in the "Submissions box&

Time:10-03

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!

CodePudding user response:

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.

  • Related