插入期间检测周期

时间:2011-05-28 23:56:05

标签: c++ boost graph

我有一张有向图。在运行时动态添加和删除新边。如果即将添加到图形的边创建一个循环,则不应添加该边。我如何用BGL做到这一点?

typedef boost::adjacency_list<
  boost::listS, boost::vecS,
  boost::directedS
  > Graph;

int main(int, char*[]){

  Graph G;
  add_edge(0, 1, G);
  add_edge(1, 2, G);
  add_edge(2, 3, G);
  add_edge(3, 0, G);  //creates cycle, should abort.

}

2 个答案:

答案 0 :(得分:2)

您需要在每次添加之前运行广度或深度优先搜索,以查看是否将形成循环。只有在添加边(u->v)并且u已经可以从v访问时,它才会形成

这是我从here

偷走的(希望工作的)代码
bool should_we_add(Graph &G) {
  typedef Graph::vertex_descriptor Vertex; 
  std::vector<int> distances(N, 0); // where N is number of vertices in your graph

  // The source vertex 
  Vertex s = boost::vertices(G)[u]; // this is your starting vertex 

  boost::breadth_first_search(G, s,
             boost::visitor(boost::make_bfs_visitor(boost::record_distances(&distances[0], boost::on_tree_edge())))); 

  if (distances[v] != 0) {
      // it is reachable, do NOT add the edge
      cout << "Cycle!" << endl;
      return false;
  }
  return true;
}

答案 1 :(得分:0)

我编辑了evgeny的代码,因为它不能编译,你和v混在一起。这些更改未被接受,因此这里的解决方案适用于我的问题。

bool should_we_add(Graph &G, int u, int v){

  std::vector<int> distances(num_vertices(G), 0);

  breadth_first_search(G, vertex(v, G),
               visitor(make_bfs_visitor(record_distances(&distances[0], on_tree_edge())))); 

  if(distances[u] != 0){
    // it is reachable, do NOT add the edge
    cout << "Cycle!" << endl;
    return false;
  }
  return true;
}