Ruby version: How to reverse traversal 2D array in ruby


  • 0
    L

    I get used to c++, so all what I can do is a similar c++ ruby code.
    I google this to find a good solution, but it seems not that easy?
    Any one can help!
    Thanks ahead.

    def calculate_minimum_hp(dungeon)
    dp = Array.new(dungeon[0].length, 2**(0.size*8) - 1)
    row = dungeon.length
    col = dungeon[0].length
    if 1 - dungeon[row-1][col-1] <= 0
       dp[col-1] = 1
    else 
       dp[col-1] = 1 - dungeon[row-1][col-1]
    end
    dungeon.each_index do |i|
        dungeon[i].each_index do |j|
            ri = row - 1 - i
            cj = col - 1 - j
            if  ri == row-1 and cj == col - 1 
                next
            end
            temp = 0
            if cj+1 < col
                temp = [dp[cj], dp[cj+1]].min
            else 
                temp = dp[cj]
            end
            if temp - dungeon[ri][cj] <= 0
                dp[cj] = 1
            else 
                dp[cj] = temp - dungeon[ri][cj];
            end
        end
    end
    dp[0]
    

    end


  • 1

    Some suggestions, pretty much keeping the algorithm and just changing the Ruby:

    def calculate_minimum_hp(dungeon)
        row = dungeon.length
        col = dungeon[0].length
        dp = [2**(0.size*8) - 1] * col
        dp[-1] = [1 - dungeon[-1][-1], 1].max
        (row-1).downto(0) do |i|
            (col-1).downto(0) do |j|
                dp[j] = [dp[j..j+1].min - dungeon[i][j], 1].max if i < row-1 || j < col-1
            end
        end
        dp[0]
    end
    

    Can be shorter with a better initialization so you don't need the special case check and can just go over the rows instead of over the row indexes.


  • 0
    L

    Hi StefanPochmann,
    Thanks a lot for all the help.
    You are my coding super star!!


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.