DAG图也成为有向无环图,拓扑排序的时间复杂度为O(V+E),其中V、E分别为顶点和边的个数。
#include <iostream>
using namespace std;
#define Maxsize 100
typedef char VertexType;
typedef int EdgeType;
typedef struct ArcNode{ //存储边
int adjvex; //该弧所指向的顶点
struct ArcNode *nextarc; //指向下一条弧
//InfoType info; //网的边权值
}ArcNode;
typedef struct VNode{
VertexType data; //顶点信息
int count; //新增部分,统计当前入度
ArcNode *firstarc; //指向第一条边的指针
}VNode;
typedef struct{
VNode adjlist[Maxsize];
int vexnum,arcnum;
}AGraph;
bool TopSort(AGraph *G){
int i,j,n=0;
Stack S;
InitStack(S); //初始化栈
ArcNode *p;
for(i=0;i<G->vexnum;i++)
if(G->adjlist[i].count==0)
Push(&S,i); //入度为0的顶点进栈
while(!IsEmpty(S)){
Pop(&S,i);
cout<<i<<endl; //输出顶点i
n++; //统计已输出顶点个数
p=G->adjlist[i].firstarc;
while(p!=NULL){
j=p->adjvex;
G->adjlist[j].count--; //i顶点引出的边所指向的顶点入度减1
if(G->adjlist[j].count==0)
Push(&S,j); //入度为0的顶点入栈
p=p->nextarc;
}
}
if(n==G->vexnum)
return true; //拓扑排序成功
else
return false; //图有环路(n<G->vexnum),拓扑排序失败
}