当前位置: 首页 > 工具软件 > JGraphT > 使用案例 >

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

赵英哲
2023-12-01

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

package edu;

import org.jgrapht.experimental.dag.DirectedAcyclicGraph;
import org.jgrapht.experimental.dag.DirectedAcyclicGraph.CycleFoundException;
import org.jgrapht.graph.DefaultEdge;
import org.jgrapht.traverse.BreadthFirstIterator;

public class HelloJgrapht {

    public static void main(String[] args) {
        DirectedAcyclicGraph<String,DefaultEdge> dag = createGraph();
        System.out.println(dag);
        System.out.println(dag.getAncestors(dag, "v1"));
        System.out.println(dag.getDescendants(dag, "v1"));
        
        BreadthFirstIterator<String, DefaultEdge> bfi = new BreadthFirstIterator<String, DefaultEdge>(dag, "v1");
        while (bfi.hasNext()) {
            System.out.println( bfi.next() );
        }
        
    }
    private static DirectedAcyclicGraph<String,DefaultEdge> createGraph(){
        DirectedAcyclicGraph<String,DefaultEdge> g = new DirectedAcyclicGraph<String,DefaultEdge>(DefaultEdge.class);
        String v1 = "v1";
        String v2 = "v2";
        String v3 = "v3";
        String v4 = "v4";
        String v5 = "v5";

        // add the vertices
        g.addVertex(v1);
        g.addVertex(v2);
        g.addVertex(v3);
        g.addVertex(v4);
        g.addVertex(v5);

        // add edges to create a circuit
        try {
            g.addDagEdge(v1, v5);
            g.addDagEdge(v5, v3);
            g.addDagEdge(v3, v4);
            g.addDagEdge(v1, v2);
            g.addDagEdge(v4, v2);
        } catch (CycleFoundException e) {
            e.printStackTrace();
        }
        return g;
    }
}

输出

([v1, v2, v3, v4, v5], [(v1,v5), (v5,v3), (v3,v4), (v1,v2), (v4,v2)])
[]
[v2, v3, v4, v5]
v1
v5
v2
v3
v4

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

 类似资料: