3
SimpleWeightedGraph<String, DefaultWeightedEdge> g = new SimpleWeightedGraph<>(DefaultWeightedEdge.class);

    String v1 = "v1";
    String v2 = "v2";
    String v3 = "v3";


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


    // add edges to create a path
    g.addEdge(v1, v2);
    g.addEdge(v2, v3);

I use the JGraphT library to create a graph containing a path from v1 to v3 via v2. How can I check if v1 is connected with v3?

Martin
  • 381
  • 4
  • 17
Jason Z
  • 265
  • 1
  • 6
  • 12

1 Answers1

4

Many ways to do it. The way I would use is to check for a shortest path. Just use the following -

DijkstraShortestPath dijk = new DijkstraShortestPath(g, startNode, endNode);
GraphPath<Integer, WeightedEdge> shortestPath = dijk.getPath();

Here g is the graph. The types in GraphPath are the same as that of g. If there is a connection, shortestPath contains the shortest path between them. If not, then shortestPath is equal to null.

stolen_leaves
  • 1,441
  • 11
  • 19