如何处理递归

How to handle recursion?

本文关键字:递归 处理 何处理      更新时间:2023-10-16

一个2D数组表示一个图像,每个像素都有一种颜色,这个递归函数的任务是将像素(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)的示例:

OOOOOO
OOVOOO
OVVVOO
OVVOOO
OVOOOO

在链接中,有一个比递归更有效的解决方案

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]);
        }
    }
}

既然你把整个东西都改成了一种颜色,为什么不使用2个嵌套的for循环呢?那么你就不必进行if语句检查,因此你的函数就不会是递归的。

试试这个:

for(int i = 0; i < y; i++){
  for(int j = 0; j < x; j++){
      arr[i][j] = newC;
  }
}