一个二维数组代表一个图像,每个像素都有一个颜色,这个递归函数的工作是将像素(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)的示例:
呜呜呜
呜呜呜
哦VVOO
哇呜呜
呜呜呜
最佳答案
因为在链接中有一个比递归更有效的解决方案
http://en.wikipedia.org/wiki/Flood_fill
填充(节点、目标颜色、替换颜色):
1. If target-color is equal to replacement-color, return.
2. Set Q to the empty queue.
3. Add node to the end of Q.
4. While Q is not empty:
5. Set n equal to the last element of Q.
6. Remove last element from Q.
7. If the color of n is equal to target-color:
8. Set the color of n to replacement-color.
9. Add west node to end of Q.
10. Add east node to end of Q.
11. Add north node to end of Q.
12. Add south node to end of Q.
13. Return.
这是我第一次尝试将伪代码转换为 C++:
std::deque<char> myqueue;
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++ - 如何处理递归?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22975648/