【发布时间】:2015-11-16 02:54:25
【问题描述】:
我需要存储在图上找到循环的所有边或顶点。在网上搜索了两天后,我越接近发现代码不起作用:
struct CycleDetector : public dfs_visitor<> {
CycleDetector(std::vector<Vertex> p, std::vector<Vertex>& _cycle) : m_predecessor(p), cycle(_cycle) { }
void back_edge(Edge e, Graph const& g)
{
Vertex t = target(e, g);
Vertex c = source(e, g);
std::cout << "(" << t << "," << c << ")" << std::endl;
std::cout << "Predecessor: " << m_predecessor[c] << std::endl;
cycle.push_back(c);
do {
c = m_predecessor[c];
cycle.push_back(c);
} while(c != t);
}
protected:
std::vector<Vertex>& cycle;
std::vector<Vertex> m_predecessor;
};
int main()
{
//after a routine to create the graph and add_edges
std::vector<Vertex> cycle;
std::vector<Vertex> p(num_vertices(g1));
CycleDetector vis(p, cycle);
depth_first_search(g1, visitor(vis));
for (int i=0; i<cycle.size(); i++)
std::cout << cycle[i] << ", ";
std::cout << std::endl;
这是程序的输出。这是一个最大度数为 2 的生成树。我在 E 和 H 顶点上添加一条边,以建议创建一个循环。我需要检测这个循环并返回形成它的所有顶点或边。
谢谢。
【问题讨论】:
-
在你的示例中,你需要将
Graph& g作为Graph const& g进行编译 -
您好。我进行了更改,代码正在运行(有时是未定义的时间),但没有给出预期的结果。你能给我更多的帮助吗?我将发布程序的输出。
标签: cycle boost-graph undirected-graph