有谁能告诉我为什么fillpool
总会崩溃?也许有一个无限的递归,但在哪里?
#include <stdio.h>
#include <stdbool.h>
#define N 5
bool IsNotValidIndex(int Row , int Column)
{
if((Row >= N || Row < 0) || (Column >= N || Column < 0))
return true ;
return false ;
}
void fillpool(int row , int column , int picture[N][N])
{
if(IsNotValidIndex(row , column))
return ;
if(picture[row][column] == 0)
return ;
picture[row][column] = 2 ;
fillpool(row + 1 , column , picture) ;
fillpool(row - 1 , column , picture) ;
fillpool(row ,column + 1 , picture) ;
fillpool(row , column -1 , picture) ;
}
答案 0 :(得分:1)
您有无限递归,因为您将行/列的值设置为“2”,然后检查它是否为“0”。所以你经常一遍又一遍地将值设置为2。无限递归的发生是因为你正在调用fillpool为“row + 1”,然后它将填充“row-1”,因此你得到无限递归(同样的事情会发生在列+ 1但你永远不会到达那里)
答案 1 :(得分:0)
代码演练可以快速解决问题,通过在调试器中单步执行代码可以轻松完成此过程。
假设您使用row = col = 2
来调用它,这会设置2,2
:
00000
00000
00200
00000
00000
然后你调用fillpool(row + 1 , column , picture)
,递归直到行无效:
00000
00000
00200
00200
00200
然后调用fillpool(row - 1 , column , picture)
来设置1,2
:
00000
00200
00200
00200
00200
然后调用fillpool(row + 1 , column , picture)
,但这指的是2,2
,因此您正处于开始状态,因此将重复上述序列,直到堆栈耗尽。
4路洪水填充算法因此(来自https://en.wikipedia.org/wiki/Flood_fill):
Flood-fill (node, target-color, replacement-color):
1. If target-color is equal to replacement-color, return.
2. If the color of node is not equal to target-color, return.
3. Set the color of node to replacement-color.
4. Perform Flood-fill (one step to the south of node, target-color, replacement-color).
Perform Flood-fill (one step to the north of node, target-color, replacement-color).
Perform Flood-fill (one step to the west of node, target-color, replacement-color).
Perform Flood-fill (one step to the east of node, target-color, replacement-color).
5. Return.
您通过测试0但填充2:
错误地编写了第1步if(picture [row] [column] == 2) 返回;