How can I create a new path
by expanding an existing one in a graph with JgraphT e.g. after I get the shortest path between two vertices, how can I expand it by inserting an adjacent node in between the vertices that make up the path? Assume I have a path that looks like that specified below:
Before Insertion
VertexList:-> [1, 29, 191, 189, 126, 243, 197]
EdgeList:-> [((1) : (29)), ((29) : (191)), ((191) : (189)), ((189) : (126)), ((126) : (243)), ((243) : (197))]
Adjacent vertex to vertex 191 -> 44
After Insertion
VertexList:-> [1, 29, 191, 44, 189, 126, 243, 197]
EdgeList:-> [((1) : (29)), ((29) : (191)), ((191) : (44)), ((44) : (189)), ((189) : (126)), ((126) : (243)), ((243) : (197))]
Currently there's no direct way to insert a vertex in an existing GraphPath
. The easiest way to accomplish what you want is to create a new GraphPath
.
//Get your shortest path
GraphPath<V,E> p1= ...;
//Copy the vertex list and insert your vertex in the desired position
List<V> vertexList=new ArrayList<>(p1.getVertexList());
vertexList.insert(position,vertex);
//Create a new GraphPath from the new vertex list
GraphPath<V,E> p2= new GraphWalk<>(graph, vertexList, weight);
The above procedure generally works well if the graph is a simple graph. Extra care must be taken when the graph is a multigraph or pseudograph! In a multigraph, there can be multiple edges between the same vertex. A path in a multigraph must be expressed in terms of its edges, rather than a sequence of vertices. E.g. the path [a,b,c,d]
expressed in its vertices is not well-defined when there are multiple edges between vertices b
and c
. So in case of a multigraph, vertex insertion has to be performed by modifying the edgeList of the path (see GraphPath.getEdgeList()
)