#include<stdio.h> 
#include<stdlib.h> 
#include<string.h>
#include<limits.h>  
#include<iostream>
using namespace std;

#define INFINITY 4270000 // 用整型最大值代替∞ 

#include"ALGraph.h"

#include"sqstack.h"

void FindInDegree(ALGraph G,int indegree[]); // 求顶点的入度

int TopologicalSort(ALGraph G);// 有向图G采用邻接表存储结构。若G无回路,则输出G的顶点的一个拓扑序列并返回1,否则返回0
	
int main()
{
	ALGraph g;
	CreateGraphF(g); // 利用数据文件创建无向图
	Display(g); // 输出无向图
	printf("输出有向图g的拓扑序列:\n");
	TopologicalSort(g); // 输出有向图f的拓扑序列  
	return 0;
}

void FindInDegree(ALGraph G,int indegree[])
{ //计算图G每个顶点的入度,并且保存在indegree数组
	int i;
	ArcNode *p;
	for(i=0;i<G.vexnum;i++)
		indegree[i]=0; /* 赋初值 */
	for(i=0;i<G.vexnum;i++)
	{
		p=G.vertices[i].firstarc;
		while(p)
		{
			indegree[p->data.adjvex]++;
			p=p->nextarc;
		}
	}
}
int TopologicalSort(ALGraph G)
{   // 有向图G采用邻接表存储结构。
	// 若G无回路,则输出G的顶点的一个拓扑序列并返回1,否则返回0。
	/********** Begin **********/    
	int i,k,count=0;                     // 已输出顶点数,初值为0 
    int indegree[MAX_VERTEX_NUM];   // 入度数组,存放各顶点当前入度数 
    SqStack S;
    ArcNode *p;
    FindInDegree(G,indegree);            // 对各顶点求入度indegree[]
    InitStack(S);                        // 初始化零入度顶点栈S 
    for(i=0;i<G.vexnum;++i)              // 对所有顶点i 
        if(!indegree[i])                  // 若其入度为0 
            Push(S,i);                  // 将i入零入度顶点栈S 
    while(!StackEmpty(S))
    {              // 当零入度顶点栈S不空 
        Pop(S,i);                     // 出栈1个零入度顶点的序号,并将其赋给i 
        printf("%s ",G.vertices[i].data);     // 输出i号顶点 
        ++count; // 已输出顶点数+1 
        for(p=G.vertices[i].firstarc; p; p=p->nextarc)
        {    // 对i号顶点的每个邻接顶点 
            k=p->data.adjvex;            // 其序号为k 
            if(!(--indegree[k]))            // k的入度减1,若减为0,则将k入栈S 
                Push(S,k);
        }
    }
    if(count<G.vexnum) 
    {               // 零入度顶点栈S已空,图G还有顶点未输出 
        printf("\n此有向图有回路\n");
        return 0;
    } 
    else    
        return 1;
	/********** End **********/
}
 
posted on 2024-06-20 17:38  findscripter  阅读(32)  评论(0)    收藏  举报