#include<stdio.h>
#include<stdlib.h>
#include<stack>
#define max 20
using namespace std;
int indegree[max];
typedef struct Arcnode{
int adj;
struct Arcnode *nextarc;
}Arcnode;
typedef struct Vnode {
int data;
Arcnode *firstarc;
}Vnode,Adjlist[max];
typedef struct{
Adjlist vertices;
int vex,arc;
}Algraph;
int Locatevex(Algraph &G,int v)
{
int i,k=-1;
for(i=0;i<G.vex;i++)
if(v==G.vertices[i].data)
{
k=i;
break;
}
return k;
}
void CreateAdjList(Algraph &G)
{ //创建图的邻接表
int i,j,k;
int v1,v2;
Arcnode *p,*s;
printf ("输入图的顶点数与边数:\n");
scanf("%d%d",&G.vex,&G.arc);
printf ("输入顶点信息:\n");
for( i=0;i<G.vex;++i) //初始化头结点
{
scanf("%d",&G.vertices[i].data);
G.vertices[i].firstarc = NULL;
}
printf ("输入一边依附的两个顶点:\n");
for( k=0;k<G.arc;++k)
{ //构造邻接表
scanf("%d%d",&v1,&v2);
i=Locatevex(G,v1);
j=Locatevex(G,v2);
s=(Arcnode*)malloc(sizeof(Arcnode));
s->adj=j;
s->nextarc=NULL;
p=G.vertices[i].firstarc;
if(!p)
G.vertices[i].firstarc=s;
else
{
while(p->nextarc)
p=p->nextarc;
p->nextarc=s;
}
}
}
void FindInDegree( Algraph &g, int indegree[])
{ //求每个顶点的入度
int i;
Arcnode *p;
for (i=0;i<g.vex;i++)
indegree[i]=0;
for (i=0;i<g.vex;i++)
{
p=g.vertices[i].firstarc;
while(p)
{
indegree[p->adj]++;
p=p->nextarc;
}
}
}
void TopologicalSort(Algraph g)
{
int count;
int k,i;
Arcnode *p;
stack<int>s;
FindInDegree(g,indegree) ; //对各顶点求入度
for(i=0;i<g.vex;i++ ) //将入度为0的顶点压入栈
if(!indegree[i])
s.push(i);
count=0;
while(!s.empty())
{
i=s.top();
s.pop();
printf ("%d ",g.vertices[i].data); //输出拓扑排序序列
count++;
for(p=g.vertices[i].firstarc;p;p=p->nextarc)
{
k=p->adj;
if (!(--indegree[k]))
s.push(k);
}
}
if(count<g.vex)
{
printf("\n该图有回路\n");
}
else
printf ("\n该图无回路\n");
}
int main()
{
Algraph g;
CreateAdjList (g);
TopologicalSort(g);
return 0;
}
判断邻接表存储的有向图是否有环
最新推荐文章于 2023-08-27 00:01:18 发布