如何在JGraphT中使用AStarShortestPath算法来计算图形的直径?

时间:2019-05-06 07:01:44

标签: a-star jgrapht

我试图编写一些代码,以结合使用AStarShortestPath算法和JGraphT来计算图形的直径,但它甚至没有计算出一条最短的路径。以下是我的一些代码来计算具有数百万个图的图形的直径顶点:

public static void main(String[] args) throws Exception {

    Graph<Integer, DefaultWeightedEdge> subGraph = createSubGraph();
    AStarAdmissibleHeuristic heuristic = new AStarAdmissibleHeuristic() {
        @Override
        public double getCostEstimate(Object o, Object v1) {
            return 4;
        }
    };

    double diameter = Double.NEGATIVE_INFINITY;
    double curr_diameter = Double.NEGATIVE_INFINITY;
    int i=0;

    for(Integer v: subGraph.vertexSet()) {
        AStarShortestPath<Integer, DefaultWeightedEdge> alg = new AStarShortestPath<>(subGraph,heuristic);
        ShortestPathAlgorithm.SingleSourcePaths<Integer, DefaultWeightedEdge> paths = alg.getPaths(v);
        for(Integer u: subGraph.vertexSet()) {
            diameter = Math.max(diameter, paths.getWeight(u));
        }
    }

    System.out.println("Graph diameter = " + diameter);
}

private static Graph<Integer, DefaultWeightedEdge> createSubGraph() throws Exception{

    Graph<Integer, DefaultWeightedEdge> g = GraphTypeBuilder
            .undirected()
            .weighted(true)
            .allowingMultipleEdges(true)
            .allowingSelfLoops(true)
            .vertexSupplier(SupplierUtil.createIntegerSupplier())
            .edgeSupplier(SupplierUtil.createDefaultWeightedEdgeSupplier())
            .buildGraph();

    int j;
    String edgepath = "sub_edge2000000.txt";
    FileReader fr = new FileReader(edgepath);
    BufferedReader bufr = new BufferedReader(fr);
    String newline = null;
    while ((newline = bufr.readLine())!=null) {
        String[] parts = newline.split(":");
        g.addVertex(Integer.parseInt(parts[0]));
    }
    bufr.close();

    fr = new FileReader(edgepath);
    bufr = new BufferedReader(fr);
    while ((newline = bufr.readLine())!=null) {
        String[] parts = newline.split(":");
        int origin=Integer.parseInt(parts[0]);
        parts=parts[1].split(" ");
        for(j=0;j<parts.length;j++){
            int target=Integer.parseInt(parts[j]);
            g.addEdge(origin,target);
        }
    }
    bufr.close();

    return g;
}

非常感谢!

0 个答案:

没有答案