Original: topological sorting of Graphs

Source: Internet
Author: User
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;
}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.