What is the best way to construct a undirected graph in java? I need to create a graph so that i could run BFS and DFS on it.The graph should include information such as path cost and adjacent edges.
Asked
Active
Viewed 132 times
1 Answers
2
You can use available libraries. For example, JgraphT is a library which provides standard graph algorithms. JgraphT provides an iterator for doing BFS, see here. Here is an simple example:
SimpleWeightedGraph<Integer, DefaultWeightedEdge> graph = new SimpleWeightedGraph<>(DefaultWeightedEdge.class);
graph.addVertex(1);
graph.addVertex(2);
graph.addVertex(3);
DefaultWeightedEdge edge = graph.addEdge(1, 3);
graph.setEdgeWeight(edge, 11.22);
edge = graph.addEdge(3, 2);
graph.setEdgeWeight(edge, 44.33);
BreadthFirstIterator<Integer, DefaultWeightedEdge> it = new BreadthFirstIterator<>(graph);
for (; it.hasNext();) {
Integer i = it.next();
System.out.println("Node: " + i);
}

schrieveslaach
- 1,689
- 1
- 15
- 32
-
@Schrieveslaach Thanks for the reply, but i want to construct a method on my own rather than using a external library. – curious_cat Sep 12 '15 at 19:01