【发布时间】:2014-05-23 10:16:53
【问题描述】:
一个二维数组代表一张图片,每个像素都有一种颜色,这个递归函数的工作就是将周围像素(x,y)的一个相同颜色(c)的区域转换成新的颜色(newC)。函数是工作正常,直到我通过像 x=200, y=200 这样的大数字并发生 SO。 我该如何处理这种情况?或者是否有比递归更好的解决方案?
void Region(int x, int y, char newC, char c) { //c is current color, newC is new Color
if(c == newC) return;
arr[y][x]=newC;
if(arr[y][x-1 ]== c && x-1 > 0) Region(x-1, y, newC, c);
if(arr[y-1][x] == c && y-1 > 0) Region(x, y-1, newC, c);
if(arr[y][x+1] == c && x+1 <= M) Region(x+1, y, newC, c);
if(arr[y+1][x] == c && y+1 <= N) Region(x, y+1, newC, c);
}
2 个区域(Os 和 Vs)的示例:
呜呜呜
呜呜呜
OVVVOO
OVVOOO
呜呜呜
【问题讨论】:
-
听起来您在谈论flood fill,在这种情况下,最好使用链接中描述的基于堆栈的递归。
-
@RogerRowland 谢谢这个链接很有帮助!如果有人告诉我代码有什么问题,我将不胜感激:
void Region(int x,int y,char newC,char c) { char n; if(c==newC)return; myqueue.empty(); myqueue.push_back(arr[y][x]); while (myqueue.size()!=0) { n=myqueue.back(); myqueue.pop_back(); if(n==c) { n=newC; if(x-1>0)myqueue.push_back(arr[y][x-1]); if(y-1>0)myqueue.push_back(arr[y-1][x]); if(x+1<=M)myqueue.push_back(arr[y][x+1]); if(y+1<=N)myqueue.push_back(arr[y+1][x]); } } }
标签: c++ recursion visual-c++ stack-overflow