// TopologicalSort.cpp : Defines the entry point for the console application.
/*-----CODE FOR FUN---------------
-------CREATED BY Dream_Whui------
-------2015-2-15--------------------*/
//拓扑排序
#include "stdafx.h"
#include "graph.h"
#include <stack>
int indegree[MAX_VERTEX_NUM];
void FindInDegree(ALGraph G, int* indegree)//求各顶点的入度
{
int i,j;
ArcNode *p;
for(i=0; i<G.vexnum; i++)
{
p = G.vertices[i].firstarc;
while(p)
{
j = p->adjvex;
indegree[j]++;
p = p->nextarc;
}
}
}
int TopologicalSort(ALGraph G)//拓扑排序
{
FindInDegree(G,indegree);
stack<int> S;
int i,j;
for(i=0; i<G.vexnum; i++)//入度为0的进栈
if(!indegree[i])
S.push(i);
int count = 0; //对输出顶点计数
ArcNode *p;
while(!S.empty())
{
j = S.top();
S.pop();
cout<<G.vertices[j].data<<"->";
++count;
for(p=G.vertices[j].firstarc; p!=NULL; p=p->nextarc)
{
j = p->adjvex; //对j号顶点的每个邻接点的入度减1
if(!(--indegree[j]))//若入度为0,则进栈
S.push(j);
}
}
if(count<G.vexnum)
return ERROR; //该图有回路
else
return OK;
}
int main(int argc, char* argv[])
{
ALGraph G;
CreateGraph(G);
TopologicalSort(G);
return 0;
}
数据结构--拓扑排序
最新推荐文章于 2022-11-06 17:47:27 发布