【发布时间】:2021-10-06 12:23:51
【问题描述】:
当我遇到这个疑问时,我正在实现一个基本版本的洪水填充算法。
你应该在递归调用之前还是递归调用之后为当前单元格着色(即image[sr][sc] = newColor)?为什么这两种方法有区别?当当前单元格在递归调用起作用之前着色但如果我更改顺序则会给出分段错误。
代码如下:
vector<vector<int>> floodFill(vector<vector<int>>& image, int sr, int sc, int newColor) {
if(image.size()<=0 || image[sr][sc] == newColor) return image;
int rows = image.size(),cols=image[sr].size();
int temp = image[sr][sc];
image[sr][sc] = newColor;
//check up
if((sr-1)>=0 && image[sr-1][sc] == temp){
image = floodFill(image,sr-1,sc,newColor);
}
//check left
if((sc-1)>=0 && image[sr][sc-1] == temp){
image = floodFill(image,sr,sc-1,newColor);
}
//check right
if((sc+1)<cols && image[sr][sc+1] == temp){
image = floodFill(image,sr,sc+1,newColor);
}
//check down
if((sr+1)<rows && image[sr+1][sc] == temp){
image = floodFill(image,sr+1,sc,newColor);
}
//if i put the image[sr][sc] = newColor; here it give seg error
return image;
}
【问题讨论】:
-
显然你应该先上色,因为后上色不起作用,你可以清楚地看到。又是什么问题?
-
下班后为什么不上色?就在返回调用函数之前,我可以着色并返回对吗?(我还是新手,也许我没有看到明显的东西?)
-
最好自己弄清楚为什么着色后不起作用。启动调试器并在 1x2 矩阵上逐步运行它。
标签: c++ algorithm recursion segmentation-fault