c++ - 如何处理递归?

标签 c++ recursion visual-c++ stack-overflow

一个二维数组代表一个图像,每个像素都有一个颜色,这个递归函数的工作是将像素(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/

相关文章:

c++ - 如何在不使用 abort() 的情况下断言()?

c++ - 寻找整数可以表示为唯一自然数的 n 次幂之和的方法。给出错误输出的代码

c++ - 在处理迭代器时使用以下内容有什么好处

c++ - "cannot access private member' "只有当类有导出链接时才会出错

c++ - 在 C++ 中同时读取和写入两个不同文件的文件流

android - Android NDK printf 输出在哪里?

java - 通过递归计算 PellNumbers。尝试实现内存 vector 失败

java - 计算树中从根到最远节点的边的方法

c++ - 在单独的数据中显示数组数据

c++ - 导致 "non-trivial designated initializers not supported"错误的结构成员顺序