Fatal Python error: Cannot recover from stack overflow. During Flood Fill

跟風遠走 提交于 2019-11-28 13:37:15

You are using a stack-based forest fire algorithm, known to eat a lot of stack, so it's better to avoid it.

My proposal to avoid recursion: alternate forest fire algorithm

I even implemented it using your class objects. Tested it with some ASCII-art and also with your actual code and it worked fine even on big zones:

def fill(self, x, y, t):
    if self.cells[(x,y)] == None:  # cannot use not: there are 0 values
        to_fill = [(x,y)]
        while to_fill:
            # pick a point from the queue
            x,y = to_fill.pop()
            # change color if possible
            self.cells[(x,y)] = t

            # now the neighbours x,y +- 1
            for delta_x in range(-1,2):
                xdx = x+delta_x
                if xdx > 0 and xdx < self.columns+1:
                    for delta_y in range(-1,2):
                        ydy = y+delta_y
                        # avoid diagonals
                        if (delta_x == 0) ^ (delta_y == 0):
                            if ydy > 0 and ydy < self.rows+1:
                                # valid x+delta_x,y+delta_y
                                # push in queue if no color
                                if self.cells[(xdx,ydy)] == None:
                                    to_fill.append((xdx,ydy))
    self.repaint()

When you pass a point, it checks if must be filled. If must be filled, it inserts it in the queue and runs a loop.

The loop just pops an item from the queue, changes its color, and attempts to do the same for its neighbors: if still in the picture (x,y boundary checking) and not the diagonals, and no color defined on the neighbour, just insert the coord in the queue.

The loops stops when all items have been processed: after a while, either you reach the edges or you encounter only filled points, so no extra points are queued.

This approach only relies on available memory, not stack.

Proof that it works: successfully filled a huge blue zone without stack overflow.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!