摘要:拓扑排序是有向无圈图的一种定点序列.
如果存在i到j的路径,那么i就必须出现在j的前面;这个理论有很多的应用.
那么我们就来看看如何实现这种排序.
(1)图的基本数据结构:图是使用邻接矩阵实现的.
#include "stdafx.h"
#include "malloc.h"
#include"队列-数组实现.h"
#define Number 10
typedef struct Listrecord *List;
typedef List Graph[Number];
struct Listrecord
{
List Next;
int Element;
};
void Initialize(Graph G)
{
int i;
for (i = 0;i<= Number-1;i++)
{
//创建头结点
G[i] = (List)malloc(sizeof(Listrecord));
G[i]->Element = i;//编号0-V-1
G[i]->Next = NULL;
}
}
void Insert(List L,int Element)//插入到L的最后一个结点
{
if (L!=NULL)
{
while(L->Next!=NULL)
{
L = L->Next;
}
L->Next = (List)malloc(sizeof(Listrecord));
L = L->Next;
L->Element = Element;
L->Next = NULL;
}
}
(2)拓扑排序的基本思路:
首先获取每个节点的入度,然后找到所有入度为0的节点,然后每次从队列里面取出一个节点,输出,并将与该节点连接的所有节点入度减1,当遇到入度为0的节点,将它入队.直到队列为空.如果存在一个圈,那么有几个节点将永远不会入队,最后检测是否输出所有节点,若没有,则代表有圈,这是不能进行排序的.
void Topsort(Graph G, int * Indegree)//拓扑排序
{
int i,counter = 0;
queue Q = Create(Number);//用来储存入度
for (i = 0;i<=Number-1;i++)
{
if(Indegree[i] == 0)
Enqueue(Q,i);
}
while (Q->size!=0)
{
printf("%d->",i = Dequeue(Q));
counter ++;
G[i] = G[i]->Next;
while(G[i]!=NULL)
{
Indegree[G[i]->Element]--;//邻接结点入度减少1
if (Indegree[G[i]->Element] == 0)
Enqueue(Q,G[i]->Element);
G[i] = G[i]->Next;
}
}
if (counter !=Number)
puts("\nerror: there is a cycle");
}
int _tmain(int argc, _TCHAR* argv[])
{
Graph G;
Initialize(G);
int Indegree[Number];
for (int i = 0;i<=Number - 1;i++)
{
if (i!=3)
{
Insert(G[i],3);
Indegree[i] = 0;
}
}
Insert(G[3],1);
Indegree[1] = 1;
Indegree[3] = 9;
Topsort(G,Indegree);
return 0;
}