lemon/bfs.h
.To use the class, declare it!
Bfs<ListUGraph> bfs(gr);
It provides a simple but powerful interface to control the execution.
int dist = bfs.run(s,t);
s
to node t
and returns it, or zero if there is no path from s
to t
.bfs.run(s);
For an example let's say we want to print the shortest path of those nodes which are in a certain distance.
bfs.run(s); for( ListUGraph::NodeIt n(gr); n != INVALID; ++n ) { if( bfs.reached(n) && bfs.dist(n) <= max_dist ) { std::cout << gr.id(n); Node prev = bfs.prevNode(n); while( prev != INVALID ) { std::cout << "<-" << gr.id(prev); prev = bfs.prevNode(n); } std::cout << std::endl; } }
run()
. Now we introduce the way you can directly control the execution of the algorithm.First you have to initialize the variables with init().
bfs.init();
Then you add one or more source nodes to the queue. They will be processed, as they would be reached by the algorithm before. And yes - you can add more sources during the execution.
And finally you can start the process with start(), or you can write your own loop to process the nodes one-by-one.
We will see a program, which solves the problem of topological ordering. We need to know in which order we should put on our clothes. The program will do the following:
First of all we will need an own ProcessedMap. The ordering will be done through it.
set()
method the only thing we need to do is insert the key - that is the node whose processing just finished - into the beginning of the list.LEMON
. But we wanted to show you, how easy is to add additional functionality.First we declare the needed data structures: the graph and a map to store the nodes' label.
Now we build a graph. But keep in mind that it must be DAG because cyclic graphs has no topological ordering.
See how easy is to access the internal information of this algorithm trough maps. We only need to set our own map as the class's ProcessedMap.
And now comes the third part. Write out the list in reverse order. But the list was composed in reverse way (with push_front()
instead of push_back()
so we just iterate it.
The program is to be found in the demo directory: topological_ordering.cc