如何处理递归
How to handle recursion?
一个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;
}
}
相关文章:
- 通过递归进行因子分解
- 递归函数计算序列中的平方和(并输出过程)
- 使用递归的数组的最小值.这是怎么回事
- 递归列出所有目录中的C++与Python与Ruby的性能
- 递归计数给定目录的文件和所有目录
- 如何在BST的这个简单递归实现中消除警告
- C++:正在检查LinkedList中的回文-递归方法-错误
- 如何处理带有变体和使用的复杂性头递归
- 使用C++的递归线程处理会使资源暂时不可用
- 如何处理和避免递归
- 如何使用void类型处理递归回溯返回
- 以嵌套或递归方式(即在处理程序内)调用 asio io_service poll() 或 poll_one() 是否有效
- 0xC0000005中0x770115de处未处理的异常:使用递归矢量搜索读取位置0xccccccc0时发生访问冲突
- 使用BOOST _PP_SEQ_FOREACH _R递归处理枚举
- 从套接字递归处理数据
- 未处理的异常排序递归
- 试图在递归函数内部捕获失败的分配:未处理的异常/堆栈溢出
- 递归n皇后程序中c++分段错误的处理
- 用c++递归解决迷宫,不能处理异常情况
- 如何处理递归