c++ - Flood Fill recursive stack overflow -
if try fill 100x100 rectangle overflow. 50x50 works fine.
is there way fix overflow?
i print out stack number , working rectangle stack higher big 1 (it crashes around 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; }
don't use recursion. instead, use stack store coordinates want draw. , iterate until stack empty.
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}); } } }
Comments
Post a Comment