1 year ago
#174724
Wrapper
Determining if graph is a tree data structure?
Problem I'm dealing with is pretty straightforward. Need to get simple true
or false
from a function.
My business domain with classes looks like this:
A
/ \
B C
/ \
D E
Probably in future this will change, so it will not be a binary tree but it will still stay a tree, where each node can have multiple children.
Since I'm not very versed with all those fancy DS, I decide to relay on tutorials and libraries. The code I came up is going like so:
import org.jgrapht.DirectedGraph;
import org.jgrapht.GraphTests;
import org.jgrapht.graph.DefaultDirectedGraph;
import org.jgrapht.graph.DefaultEdge;
import org.jgrapht.graph.AsUndirectedGraph;
import org.jgrapht.GraphTests;
@GetMapping("/b/{vertices}")
public Object test2(@PathVariable("vertices") String vertices) throws IOException {
List<String> possibleVertices = Arrays.stream(vertices.split(",")).collect(Collectors.toList());
DirectedGraph<String, DefaultEdge> directedGraph = new DefaultDirectedGraph<>(DefaultEdge.class);
possibleVertices.forEach(directedGraph::addVertex);
if (possibleVertices.contains("A") && possibleVertices.contains("B")){
directedGraph.addEdge("A", "B");
}
if (possibleVertices.contains("A") && possibleVertices.contains("C")){
directedGraph.addEdge("A", "C");
}
if (possibleVertices.contains("C") && possibleVertices.contains("D")){
directedGraph.addEdge("C", "D");
}
if (possibleVertices.contains("C") && possibleVertices.contains("E")){
directedGraph.addEdge("C", "E");
}
AsUndirectedGraph<String, DefaultEdge> unidirected = new AsUndirectedGraph<>(directedGraph);
return GraphTests.isTree(unidirected );
}
I tested all combinations and code is working as expected. However I do have couple of questions:
- Is this library meant to use it in this way? That is, is mapping between vertices meant to be done in this manner?
- Why do I need to convert from directed to undirected graph?
- Since I'm working with Spring Boot, is it safe to use
@Bean
for creatingdirectedGraph
,unidirected
(possibly providing vertices to bean through lambda or something similar?) I do have doubts if those vertices withaddVertex
are not cached in some map within that object I'm invoking to construct the graph? - Is creation of any *grpah with
new
using this library expansive?
java
data-structures
tree
directed-graph
undirected-graph
0 Answers
Your Answer