【问题标题】:Detecting Cycles During Insertion在插入期间检测循环
【发布时间】:2011-05-28 23:56:05
【问题描述】:

我有一个有向图。在运行时动态添加和删除新边。如果将要添加到图中的边创建了一个循环,则不应添加该边。我将如何使用 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.

}

【问题讨论】:

    标签: c++ boost graph


    【解决方案1】:

    您需要在每次添加之前运行广度或深度优先搜索,以查看是否会形成一个循环。 当且仅当您要添加边 (u-&gt;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;
    }
    

    【讨论】:

    • 我认为你把 u 和 v 弄混了,但你的代码仍然有错误。不过,谢谢。
    【解决方案2】:

    我编辑了 evgeny 的代码,因为它无法编译,并且 u 和 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;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-05-20
      • 2013-10-29
      • 2020-10-20
      • 2013-10-06
      相关资源
      最近更新 更多