Question
I am experimenting with JGraphT and have hit a brick wall trying to implement a depth first search using the JGraphT API. I have created a simple graph with nodes and vertices's as follows:
- DirectedGraph
graph = new - DefaultDirectedGraph
(DefaultEdge.class); - graph.addVertex(7);
- graph.addVertex(4);
- graph.addVertex(9);
- graph.addVertex(3);
- graph.addVertex(2);
- graph.addVertex(5);
- graph.addEdge(7, 4);
- graph.addEdge(7, 9);
- graph.addEdge(9, 3);
- graph.addEdge(3, 2);
- graph.addEdge(3, 5);
How-To
Just traverse the graph using DepthFirstIterator. Here is an example:
- package lab;
- import static org.junit.Assert.*
- import org.jgraph.graph.DefaultEdge
- import org.jgrapht.UndirectedGraph
- import org.jgrapht.graph.SimpleGraph
- import org.jgrapht.traverse.DepthFirstIterator
- import org.jgrapht.traverse.GraphIterator
- UndirectedGraph
graph = - new SimpleGraph
(DefaultEdge. class); - // Graph
- // 0-----1
- // |
- // +---2
- // |
- // +-------6---+
- // | |
- // | +---3 |
- // +---5 + |
- // +---4---+
- 7.times{
- graph.addVertex(it);
- }
- def edges = [:]
- edges[0]=[1,2,5,6]
- edges[3]=[4,5]
- edges[4]=[6,5]
- edges.each{ k, v->
- v.each{
- graph.addEdge(k, it)
- }
- }
- GraphIterator
iterator = - new DepthFirstIterator
(graph, 0); - while (iterator.hasNext()) {
- System.out.printf("%d ", iterator.next());
- }
- println()
Supplement
* Coursera - Algorithms, Part II - Depth First Search
* [ DS & Algorithm in C++ ] Section 9.6 : Applications of Depth-First Search
* [ Algorithm ] Maze problem - Using Online DFS Search
* [ Intro Alg ] Elementary Graph Algorithms - Depth-first search
沒有留言:
張貼留言