连接的组件不适用于大矩阵尺寸
connected components not working for large matrix size
我有这段代码,用于在二进制图像中查找所有连接的组件以及该组件中的像素总数。
int isSafe(unsigned char *M, int row, int col, bool visited[][COL])
{
return (row >= 0) && (row < ROW) && (col >= 0) && (col < COL) &&
(M[row*ROW + col] && !visited[row][col]);
}
void DFS(unsigned char *M, int row, int col, bool visited[][COL])
{
indexes.push_back(count_elements);//
indexes.at(count_elements)= ((row+1)*ROW + col+1);
++count_elements;
//add index positions to array or vector
static int rowNbr[] = {-1, -1, -1, 0, 0, 1, 1, 1};
static int colNbr[] = {-1, 0, 1, -1, 1, -1, 0, 1};
visited[row][col] = true;
for (int k = 0; k < 8; ++k)
if (isSafe(M, row + rowNbr[k], col + colNbr[k], visited) )
{
DFS(M, row + rowNbr[k], col + colNbr[k], visited);
}
}
int countComponents(unsigned char *M)
{
bool visited[ROW][COL];
memset(visited, 0, sizeof(visited));
for (int i = 0; i < ROW; ++i)
for (int j = 0; j < COL; ++j)
if (M[i*ROW + j] && !visited[i][j])
{
//indexes.clear();
count_elements=0;
DFS(M, i, j, visited);
elements[count] = count_elements;
++count;
}
/*for (int i = 1; i < ROW; ++i)
{
if(elements[0]<elements[i])
elements[0] = elements[i];
}*/
//printf("%d ", elements[0]);
return count;
}
M 是大小为 512x512 的图像。 elements[] 存储每个连接的组件中的像素总数,索引矢量存储连接的像素的索引。如果任何连接的组件中的像素总数小于3200(大约),则上面的代码工作正常。但是,如果此值大于 3200,则此代码不起作用。请帮帮我。
您的堆栈大小已用完。使用Visual Studio的默认值,即使只有一个参数是int的函数也只能递归4711时间(调试模式,我的电脑)。你传递了更多的参数,并且你在堆栈上放了很多数据(bool visited[ROW][COL] - 也许还有更多未发布的代码)。因此,在对DFS进行几千次递归调用后,您会出现堆栈溢出(尽管实际崩溃可能出现在new()中)。一些替代解决方案:
-
通过命令行或链接器选项更改堆栈大小。这是非常不推荐的
-
使用向量作为堆栈(直接或使用 std::stack 适配器)而不是递归。这意味着,DPS 不需要递归,只需保留一个非开发点的向量,取最后一个,找到所有未访问的邻居,emplace_back它们,等等。
-
使用更好的连接组件算法
相关文章:
- OpenGL - 在 NDC 中计算位置适用于着色器,但不适用于'regular'程序
- 使用模板参数重载C++方法:如何使其适用于模板的子类?
- 如何修复我的最大公约数代码?它适用于除零和零以外的所有数字
- 选择排序C++(已修改)并非适用于所有情况
- 无法让"std::enable_if"适用于无作用域枚举
- 请找出我的代码中的错误,它在提交得到错误答案的同时仍然适用于我的所有测试用例
- 确定夏令时是否适用于特定日期
- 是否有一种 STL 算法可以最后找到,但它也适用于指针?
- QT 样式表主题,适用于使用属性选择器的整个应用程序
- C++带有适用于左值和右值的引用参数的函数
- 代码适用于调试,但不适用于发布
- C++17 和更新的 std::分配器是否适用于动态数量的自定义堆?
- 适用于大型数组的无复制线程安全环形缓冲区
- NRVO 是否也适用于协程?
- 约束包容是否仅适用于概念?
- 程序只适用于包含(无副作用)cout声明
- 适用于频繁更改的大型数据集的最佳数据结构
- 相同的 for 循环适用于其他项目,但不适用于此项目。为什么?
- 无法让 FastNoise 适用于草地
- 其中列 = 值,仅适用于整数值