小编Don*_*ong的帖子

在C++中实现深度优先搜索时避免堆栈溢出

网格中三角形面的连通分量

\n

我已经使用上面的链接实现了深度优先搜索,并且对于我的大多数数据样本都运行良好。当我的数据样本非常大时,代码会达到断点,由于递归函数变得太深,可能会导致堆栈溢出。有什么办法可以避免这种情况吗?或者我是否必须使用其他方式(例如广度优先搜索/并集查找算法)来查找图中的连接组件。

\n
#include <bits/stdc++.h>\nusing namespace std;\n \nclass Graph {\n \n    // A function used by DFS\n    void DFSUtil(int v);\n \npublic:\n    int count;\n    map<int, bool> visited;\n    map<int, list<int> > adj;\n    // function to add an edge to graph\n    void addEdge(int v, int w);\n \n    // prints DFS traversal of the complete graph\n    void DFS();\n};\n \nvoid Graph::addEdge(int v, int w)\n{\n    adj[v].push_back(w); // Add w to v\xe2\x80\x99s list.\n}\n \nvoid Graph::DFSUtil(int v)\n{\n    // Mark the current node as visited and print it\n …
Run Code Online (Sandbox Code Playgroud)

c++ stack-overflow recursion graph-theory depth-first-search

0
推荐指数
1
解决办法
461
查看次数