【考研】拓扑排序

算法思路:

(1) 从有向图中选择一个没有前驱(入度为0)的顶点输出;

(2) 删除①中的顶点,并且删除从该顶点出发的全部边;

(3) 重复上述两步,直到剩余的图不存在没有前驱的顶点为止;

#define INF 0x3f3f3f3f 
#define maxSize 1005
typedef struct ArcNode{ int vex; //该边所指向的结点位置 struct ArcNode*nextarc; //指向下一条边的指针 }ArcNode;
typedef
struct VNode{ int count; //顶点当前的入度 struct ArcNode*firstarc;//指向第一条边的指针 }VNode;
typedef
struct LGraph{ int n,e; struct VNode adjlist[maxSize]; }LGraph;
int TopSort(LGraph*g) { int i,j,n=0; int stack[maxSize],top=-1; ArcNode*p; //将图中入度为0的顶点入栈 for(i=0;i<g->n;i++) if(g->adjlist[i].count==0) stack[++top]=i; //由该顶点引出的边所指向顶点的入度均-1 while(top!=-1) { i=stack[top--]; n++; cout<<i<<" "; p=g->adjlist[i].firstarc; while(p!=NULL) { j=p->vex; (g->adjlist[j].count)--; if(g->adjlist[j].count==0) stack[++top]=j; p=p->nextarc; } } if(n==g->n)return 1; else return 0; }

 

转载于:https://www.cnblogs.com/kannyi/p/9410990.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值