1#include <iostream>2#include <queue>3#include <string>4 using namespacestd;5 6 //Table Nodes7typedefstructarcnode{8 intAdjvex;//The position of the vertex to which the arc is pointing9Arcnode *Nextarc;Ten }arcnode; One A //Head knot Point -typedefstructvnode{ - stringData//Vertex Information theArcnode *firstarc;//address of the first table node, pointer to the first arc attached to the vertex -}vnode, adjlist[Ten]; - -typedefstructalgraph{ + adjlist vertices; - intVexnum, Arcnum; + }algraph; A at intLocatevex (Algraph G,stringU//returns the position of the vertex u in the diagram - { - for(intI=0; i<g.vexnum; i++) - if(g.vertices[i].data==u) - returni; - return-1; in } - to voidCREATEDG (Algraph &g)//construct a map with direction + { - stringv1, v2; the intI, J, K; *cout<<"Please enter the number of vertices and the number of sides:"; $Cin>>g.vexnum>>G.arcnum;Panax Notoginseng -cout<<"Please enter a vertex:"; the for(i=0; i<g.vexnum; i++) + { ACin>>G.vertices[i].data; theG.vertices[i].firstarc=NULL; + } - $cout<<"Please enter an edge:"<<Endl; $ for(k=0; k<g.arcnum; k++) - { -Cin>>v1>>v2; theI=Locatevex (G, v1); -j=Locatevex (G, v2);Wuyi thearcnode* arc=NewArcnode; -arc->adjvex=J; WuArc->nextarc=G.vertices[i].firstarc; -G.vertices[i].firstarc=arc; About } $ } - - voidFindindegree (Algraph G,intIndegree[])//seeking the degree of vertex - { A for(intI=0; i<g.vexnum; i++) +indegree[i]=0; the - for(i=0; i<g.vexnum; i++) $ { theArcnode *p=G.vertices[i].firstarc; the while(P) the { theindegree[p->adjvex]++; -P=p->Nextarc; in } the } the } About the voidTopologicalsort (Algraph G)//Topological sorting the { thequeue<int>Q; + intindegree[Ten]={0};//into degrees group - intCount=0;//count the number of the queue the Bayi Findindegree (G, indegree); the the for(intI=0; i<g.vexnum; i++)//queue with a vertex with a 0-degree entry - if(0==Indegree[i]) - Q.push (i); the the while(!q.empty ()) the { the intv=Q.front (); - Q.pop (); thecount++; thecout<<g.vertices[v].data<<" "; theArcnode *p=G.vertices[v].firstarc;94 while(p)//after the team, each adjacency point is reduced by 1 the { the if(! (--indegree[p->Adjvex])) theQ.push (P->adjvex);//queue with a vertex with a 0-degree entry98P=p->Nextarc; About - }101 }102 103 if(Count<g.vexnum)//This will determine if there is a loop in the graph .104cout<<"the graph has a loop ."<<Endl; the }106 107 voidMain ()108 {109 algraph G; the createdg (G);111 thecout<<"topology Ordering:";113 Topologicalsort (G); thecout<<Endl; the the 117 118}
View Code
Test Case One:
Test Case Two:
Topological sequencing to determine if there is a loop in the graph