Algorithmic Solutions > LEDA > LEDA Guide > Graphs and Related Data Types > Example Graphs and Related Data Types
 
        
      Example: Topological SortingThe following program demonstrates how graphs 
        and the related data types of LEDA can be used. The program consists 
        of a function  A topological ordering  The  The function  
#include <LEDA/graph/graph.h>
#include <LEDA/graph/graph_gen.h>
#include <LEDA/core/queue.h>
using namespace leda;
bool TOPSORT (const graph& G, node_array<int>& ord) 
{
  node_array<int> INDEG(G);
  queue<node> ZEROINDEG;	
		
  node v;
  forall_nodes(v,G) {
    INDEG[v]=G.indeg(v);
    if (INDEG[v]==0) ZEROINDEG.append(v); 
  }
  int count=0;
  while (!ZEROINDEG.empty()) {
    v=ZEROINDEG.pop();
    ord[v]=++count;
			
    edge e;
    forall_out_edges(e,v) {
      node w=G.target(e);
      if (--INDEG[w]==0) ZEROINDEG.append(w);
    }
  }
	
  return (count==G.number_of_nodes());
}
 int main()
{
  graph G;
  node v[5];
  int i;for (i=0;i<5;i++) v[i]=G.new_node();
  G.new_edge(v[3],v[0]);
  G.new_edge(v[0],v[1]);
  G.new_edge(v[0],v[2]);
  G.new_edge(v[1],v[4]);
  G.print();
  node_array<int> ord(G);
  bool acyclic= TOPSORT(G,ord);
  if (acyclic) {
    node v;
    forall_nodes(v,G) {
      G.print_node(v);
      std::cout << ": " << ord[v] << "\t";
    }
	std::cout << std::endl;
  }
  else std::cout << "graph is cyclic!\n";
  return 0;
}  
       | 
     
      See also:Manual Entries:  |