Recursive version:
Void printout (int v)
{
Cout <"now visiting is:" <v <Endl;
}
Void tophelp (graph * g, int v) // use the DFS Algorithm
{
G-> setmark (v, visited );
For (int w = G-> first (V); W <G-> N (); W = G-> next (V, W ))
{
If (G-> getmark (w) = unvisited)
Tophelp (G, W );
}
Printout (v );
}
Void topsort (graph * g)
{
Int I;
For (I = 0; I <G-> N (); I ++)
G-> setmark (I, unvisited); // you can specify no access for each vertex.
For (I = 0; I <G-> N (); I ++)
If (G-> getmark (I) = unvisited)
Tophelp (G, I );
}
Int main ()
{
File * FID;
String file_name;
Cout <"Please enter the file name :";
Cin> file_name;
If (FID = fopen (file_name.c_str (), "RT") = NULL)
{
Cout <"errors have happened when open the file./N ";
Exit (1 );
}
Graphm * g = new graphm (FID );
G-> GPRS int (g );
Topsort (g );
System ("pause ");
Return 0;
}
Non-recursive version:
Void printout (INT v ){
Cout <"now visiting is: J" <v + 1 <Endl;
}
Void topsort (graph * g, queue <int> * q ){
Int count [G-> N ()];
Int V, W;
For (V = 0; v <G-> N (); V ++) Count [v] = 0; // initialize
For (V = 0; v <G-> N (); V ++) // process every edge
For (W = G-> first (V); W <G-> N (); W = G-> next (V, W ))
Count [w] ++; // Add to V2's prereq count
For (V = 0; v <G-> N (); V ++) // initialize queue
If (count [v] = 0) // vertex has no prerequisites
Q-> push (v );
While (! Q-> Empty () {// process the vertices
V = Q-> Front ();
Q-> POP ();
Printout (V); // previsit for vertex v
For (W = G-> first (V); W <G-> N (); W = G-> next (V, W )){
Count [w] --; // one less prerequisite
If (count [w] = 0) // This vertex is now free
Q-> push (w );
}
}
}
Int main ()
{
File * FID;
String file_name;
Cout <"Please enter the file name :";
Cin> file_name;
If (FID = fopen (file_name.c_str (), "RT") = NULL)
{
Cout <"errors have happened when open the file./N ";
Exit (1 );
}
Graphm * g = new graphm (FID );
G-> GPRS int (g );
Queue <int> * q = new queue <int> ();
Topsort (G, q );
System ("pause ");
Return 0;
}