#include<stdio.h>
#define Maxsize 100
#define INF 100
typedef struct {
int edge[Maxsize][Maxsize];//邻接矩阵
int count[Maxsize];//各顶点入度
int n,e;//顶点数、边数
}MGraph;
int TopSort(MGraph g){
int i,j,n=0,top=-1;
int stack[Maxsize];
//将所有入度为0的定点入栈
for(i=0;i<g.n;i++){
if(g.count[i]==0)
stack[++top]=i;
}
while(top!=-1){
i=stack[top--];
printf("%d ",i);
n++;
//将出栈顶点从图中移除并重进计算各顶点的入度
for(j=0;j<g.n;j++){
if(g.edge[i][j]!=0&&g.edge[i][j]!=INF){
g.count[j]--;
if(g.count[j]==0)
stack[++top]=j;
}
}
}
//有向图无环路
if(n==g.n)
return 1;
//有向图有环路
else
return 0;
}
int main(){
int i,j,m,n,a,b,c,d;
MGraph g;
g.n=4;g.e=4;
memset(g.edge,0,sizeof(g.edge));
memset(g.count,0,sizeof(g.count));
//初始化邻接矩阵
for(i=0;i<g.e;i++){
scanf("%d %d %d",&a,&b,&c);
g.edge[a][b]=c;
}
for(i=0;i<g.n;i++)
for(j=0;j<g.n;j++){
if(i==j)
g.edge[i][j]==0;
else if(g.edge[i][j]==0)
g.edge[i][j]=INF;
}
//初始化各顶点的入度
for(i=0;i<g.n;i++)
for(j=0;j<g.n;j++){
if(g.edge[i][j]!=0&&g.edge[i][j]!=INF)
g.count[j]++;
}
printf("%d",TopSort(g));
}
TopSort(学习记录)
最新推荐文章于 2024-08-30 22:20:44 发布
![](https://img-home.csdnimg.cn/images/20240711042549.png)