我需要的是存储在图表上找到循环的所有边或顶点。在网上搜索了两天之后,我得到的更接近的代码是无效的代码:
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顶点上添加一条边,建议创建一个循环。我需要检测这个循环并返回形成它的所有顶点或边。
感谢。
答案 0 :(得分:1)
我希望它可以提供帮助
struct MyVisitor : default_dfs_visitor {
MyVisitor(EdgeSet& tree_edges, std::vector<Vertex>& _cycle) : tree_edges(tree_edges), cycle(_cycle) {}
void tree_edge(Edge e, const Graph& g) {
std::cerr << "tree_edge " << e << std::endl;
tree_edges.insert(e);
Vertex t = target(e, g);
Vertex c = source(e, g);
m_predecessor[t] = c;
}
void back_edge(Edge e, const Graph& g) {
if (tree_edges.find(e) == tree_edges.end()) {
std::cerr << "back_edge " << e << std::endl;
Vertex t = target(e, g);
Vertex c = source(e, g);
std::cout << "(" << name[t] << "," << name[c] << ")" << std::endl;
cycle.push_back(c);
do {
c = m_predecessor[c];
cycle.push_back(c);
} while(c != t);
}
}
private:
EdgeSet& tree_edges;
public:
std::vector<Vertex>& cycle;
map<Vertex, Vertex> m_predecessor;
};
int main() {
//routine that add the edges and other things
EdgeSet tree_edges;
std::vector<Vertex> cycle;
MyVisitor vis(tree_edges, cycle);
depth_first_search(g1, visitor(vis));
for (int i=0; i<cycle.size(); i++)
std::cout << cycle[i] << ", ";
std::cout << std::endl;
谢谢!