Ruby:堆栈级别太深(SystemStackError)

ibo*_*oss 0 ruby algorithm stack

我试着解决这个问题http://www.nattee.net/~dae/algo/prob/hw03b_tiling/problem.pdf

所以我使用分而治之的方法来解决它,但是当我执行我的程序时,我得到了

tile.rb:7: stack level too deep (SystemStackError)
Run Code Online (Sandbox Code Playgroud)

这是我的代码

def tile (x, y, bx, by, ex, ey)
    mx = (bx+ex)/2
    my = (by+ey)/2

    if (by<=y && y<=my)
        if (bx<=x && x<=mx) # top-left
            puts "0 #{mx} #{my}"
        elsif (mx+1<=x && x<=ex) # top-right
            puts "1 #{mx} #{my}"
        end
    elsif (my+1<=y && y<=ey)
        if (bx<=x && x<=mx) # bottom-left
            puts "2 #{mx} #{my}"
        elsif (mx+1<=x && x<=ex) # bottom-right
            puts "3 #{mx} #{my}"
        end
    end

    tile(x,y,bx,by,mx,my) #top-left
    tile(x,y,mx+1,by,ey,my) #top-right
    tile(x,y,bx,my+1,mx+1,ey)   #bottom-left
    tile(x,y,mx+1,my+1,ex,ey) #bottom-right

    if ex-bx == 2 && ey-by == 2 then return end
end

temp = []
gets.chomp.strip.split(" ").each do |item|
temp << item.to_i
end

L = temp[0]
x = temp[1]
y = temp[2]

tile(x,y,0,0,L-1,L-1)
Run Code Online (Sandbox Code Playgroud)

我找不到原因.

DGM*_*DGM 6

没有办法退出你的递归 - 对于每次通话tile,它将再拨打4次tile.在递归调用之前,递归始终需要一个"安全阀" .return在tile通话前尝试移动你的电话.

返回声明可以写成更惯用的红宝石.

尝试:

return if (ex-bx == 2 && ey-by == 2)
Run Code Online (Sandbox Code Playgroud)