Task 1: Topological sequencing
1) Use one in-degree group Indegree to record the number of degrees each vertex is in, and use a variable to record how many vertices have been accessed
2) Press the vertex with a degree of 0 into the stack
3) Delete the element at the top of the stack. The number of vertices accessed is added by 1 and the in degrees of all vertices adjacent to the vertex are reduced by 1, and if the in degree after minus 1 is 0, it is pressed into the stack;
4) Repeat the process above until the elements in the stack are empty.
5) Read whether the number of vertices accessed is equal to the number of vertices of the graph to see if the topology sort succeeds
Implementation code:
status Topologicalsort (Algraph G) {//graph G with adjacency table storage structure//If G has no loop, it returns a topological sequence of the vertices of G and returns OK, otherwise the error is returnedFinddegree (G,indegree); Initstack (s); for(i=0; i<g.vexnum;++i)if(!Indegree[i]) push (s,i); Count=0; while(!Stackempty (s)) {pop (s,i); cout<<s<<' '; ++count; for(p=g.vetices[i].furstarc;p;p=p->next) {k=p->Adjvex; if(! (--Indegree[k])) Push (S,K); } } if(count<g.vexnum) cout<<error<<Endl; Elsecout<<success<<Endl;}
2 Depth-First traversal
intVisited[n];voidDFS (Graph G,intv) {Visited[v]=1; cout<<v<<' '; for(W=firstadjvex (g,v), w>=0; w=Nextadjvex (g,v,w)) { if(!Visited[w]) DFS (G,W); }}voidDfssearch (Graph G) { for(v=0; v<g.vexnum;++v) vistied[v]=0; for(v=0; v<g.vexnum;++v) DFS (g,v);}
3 Breadth-First traversal
intVisited[n];voidBfssearch (Graph G) { for(v=0; v<g.vexnum;++v) visited[v]=0; Initqueue (Q); for(v=0; v<g.vexnum;v++) { if(!Visited[v]) {Visited[v]=1; cout<<v<<' '; Enqueue (Q,V); while(!Queueempty (Q)) {DeQueue (q,u); for(W=firstadjvex (g,u); w>=0; w=Nextadjvex (g,u,w)) { if(!Visited[w]) {Visited[w]=1; cout<<w<<' '; EnQueue (Q,W); } } } } }}
Data structure and algorithm--graph theory