如果我尝试填充100x100矩形,则会溢出。
50x50可以正常工作。

有办法解决溢出问题吗?

我还会打印出堆栈编号,有时工作矩形堆栈要比大矩形堆栈高(它崩溃了大约7000个)。

void draw(int x, int y)
{
if ((x >= 0 && x < 100) && (y >= 0 && y < 100))
    {
            canvas.set_pixel(x, y);
            if (!canvas.get_pixel(x, y + 1))draw(x, y + 1);
            if (!canvas.get_pixel(x, y-1))draw(x, y - 1);
            if (!canvas.get_pixel(x - 1, y))draw(x - 1, y);
            if (!canvas.get_pixel(x+1, y))draw(x + 1, y);

    }

    return;
}

最佳答案

不要使用递归。而是使用堆栈存储要绘制的坐标。并迭代直到堆栈为空。

void draw(int x, int y)
{
    struct coordinate { int x, y; };
    std::stack<coordinate> to_draw;
    to_draw.push({x, y});

    while (!to_draw.empty())
    {
        auto top = to_draw.top();
        to_draw.pop();
        if (  (top.x >= 0 && top.x < 100)
           && (top.y >= 0 && top.y < 100)
           && !canvas.get_pixel(top.x, top.y))
        {
            canvas.set_pixel(top.x, top.y);
            to_draw.push({top.x, top.y + 1});
            to_draw.push({top.x, top.y - 1});
            to_draw.push({top.x + 1, top.y});
            to_draw.push({top.x - 1, top.y});
        }
    }
}

09-30 15:48
查看更多