当前位置:   article > 正文

利用JGrapht对有向无环图进行广度优先遍历

jgrapht dag

环境需求:JDK:1.8
jar:jgrapht-core-1.01.jar

  1. package edu;
  2. import org.jgrapht.experimental.dag.DirectedAcyclicGraph;
  3. import org.jgrapht.experimental.dag.DirectedAcyclicGraph.CycleFoundException;
  4. import org.jgrapht.graph.DefaultEdge;
  5. import org.jgrapht.traverse.BreadthFirstIterator;
  6. public class HelloJgrapht {
  7. public static void main(String[] args) {
  8. DirectedAcyclicGraph<String,DefaultEdge> dag = createGraph();
  9. System.out.println(dag);
  10. System.out.println(dag.getAncestors(dag, "v1"));
  11. System.out.println(dag.getDescendants(dag, "v1"));
  12. BreadthFirstIterator<String, DefaultEdge> bfi = new BreadthFirstIterator<String, DefaultEdge>(dag, "v1");
  13. while (bfi.hasNext()) {
  14. System.out.println( bfi.next() );
  15. }
  16. }
  17. private static DirectedAcyclicGraph<String,DefaultEdge> createGraph(){
  18. DirectedAcyclicGraph<String,DefaultEdge> g = new DirectedAcyclicGraph<String,DefaultEdge>(DefaultEdge.class);
  19. String v1 = "v1";
  20. String v2 = "v2";
  21. String v3 = "v3";
  22. String v4 = "v4";
  23. String v5 = "v5";
  24. // add the vertices
  25. g.addVertex(v1);
  26. g.addVertex(v2);
  27. g.addVertex(v3);
  28. g.addVertex(v4);
  29. g.addVertex(v5);
  30. // add edges to create a circuit
  31. try {
  32. g.addDagEdge(v1, v5);
  33. g.addDagEdge(v5, v3);
  34. g.addDagEdge(v3, v4);
  35. g.addDagEdge(v1, v2);
  36. g.addDagEdge(v4, v2);
  37. } catch (CycleFoundException e) {
  38. e.printStackTrace();
  39. }
  40. return g;
  41. }
  42. }

输出

  1. ([v1, v2, v3, v4, v5], [(v1,v5), (v5,v3), (v3,v4), (v1,v2), (v4,v2)])
  2. []
  3. [v2, v3, v4, v5]
  4. v1
  5. v5
  6. v2
  7. v3
  8. v4

转载于:https://www.cnblogs.com/xigui/p/6407764.html

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/从前慢现在也慢/article/detail/152200?site
推荐阅读
相关标签
  

闽ICP备14008679号