现在的位置: 首页 > 综合 > 正文

有向图的拓扑排序算法的C程序实现代码

2013年08月18日 ⁄ 综合 ⁄ 共 2058字 ⁄ 字号 评论关闭

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

//该结构体用来表示从某个顶点可以到达的其他顶点
struct ENode
{
    int secPoint;//顶点号
    ENode *next;//指向下一个顶点的指针
};

//该结构体表示每一个顶点的信息
struct PNode
{
    char value;//顶点的值
    int inDegree;
    int outDegree;
    ENode *next;//指向顶点可以到达的其他第一个顶点的指针
};

//图的结构体,该图最多有100个顶点
struct Map
{
    PNode point[100];//数组的下标就是这个顶点的顶点号
    int numPoint,numEdge;
};

//建图的函数
struct Map *CreateMap()
{
    struct Map *mp = (struct Map*)malloc(sizeof(struct Map));
    int i,j;
    int firP,secP;
    int numP,numE;
    char infoP;

    memset(mp,0,sizeof(struct Map));

    printf("请输入顶点数和边数,格式为‘顶点数,边数’:\n");
    scanf("%d,%d",&numP,&numE);
    mp->numPoint = numP;
    mp->numEdge = numE;

    printf("请输入各个顶点的信息,没有分隔符的连续输入:\n");
    fflush(stdin);
    for(i=0;i<mp->numPoint;i++)
    {
        scanf("%c",&infoP);
        mp->point[i].value = infoP;
    }

    printf("请输入边,格式为‘顶点-顶点’\n");
    fflush(stdin);
    for(j=0;j<mp->numEdge;j++)
    {
        scanf("%d-%d",&firP,&secP);
        struct ENode *newNode = (struct ENode *)malloc(sizeof(struct ENode));
        mp->point[firP].outDegree++;
        mp->point[secP].inDegree++;
        newNode->secPoint = secP;
        newNode->next = mp->point[firP].next;
        mp->point[firP].next = newNode;
    }
    return mp;
}

//拓扑排序

void TopSort(struct Map *mp)
{
    int iPoint,iNoInPoint;
    int noInPoint[20];
    int curPoint;

    struct ENode *pNode;

//将初始状态入度为0的节点放入数组

    for(iPoint=0,iNoInPoint=0;iPoint<mp->numPoint;iPoint++)
    {
        if(mp->point[iPoint].inDegree==0)
        {
            noInPoint[iNoInPoint]=iPoint;
            iNoInPoint++;
        }
    }
    iNoInPoint--;
//如果数组不为空就输出数组中最后一个元素,然后做相应操作
    printf("\n拓补排序序列:\n");
    while(iNoInPoint>=0)
    {
        curPoint = noInPoint[iNoInPoint];
        printf("%d",curPoint);

        iNoInPoint--;

//循环遍历输出节点所能到达的每一个节点,并将这些节点的入度减一

        for(pNode=mp->point[curPoint].next;pNode!=NULL;pNode=pNode->next)
        {

            mp->point[pNode->secPoint].inDegree--;

//如果某个节点入度减少为0,则加入到数组中

            if(mp->point[pNode->secPoint].inDegree==0)
            {
                iNoInPoint++;
                noInPoint[iNoInPoint] = pNode->secPoint;
            }
        }
    }
    printf("\n");
}

int main()
{
    struct Map *mp = CreateMap();
    TopSort(mp);

    return 1;
}

抱歉!评论已关闭.