拓扑排序用于对有向无循环图中,节点的遍历必须满足指向它的所有边的另一个节点都已经遍历完毕的情况。如生产过程中某些子工程必须在另一些子工程完工之后。下面是实现代码:
预定义和条件定义:
#define OK 1
#define ERROR 0
#define MVNum 100
typedef int Status;
typedef char VerTexType;
typedef char OtherInfo;
typedef struct StackNode{
int data;
StackNode *next;
}StackNode,*StackList;
typedef struct ArcNode{
int adjvex;
ArcNode *nextarc;
OtherInfo info;
}ArcNode;
typedef struct VNode{
VerTexType data;
ArcNode *firstarc;
}VNode,AdjList[MVNum];
typedef struct{
AdjList vertices;
int vexnum, arcnum;
}ALGraph;
并声明一个int 类型的indegree[]数组,初始化为0:
int indegree[MVNum] = {0};
用于记录下标节点的入度。
入栈函数:
StackList Push(StackList S,int e)
{
StackList p;
p = (StackNode *)malloc(sizeof(StackNode));
p->data = e;
p->next = S;
S = p;
return S;
}
出栈函数:
StackList Pop(StackList S, int *e)
{
StackList p;
p = S;
if (!p)
return ERROR;
*e = p->data;
S = S->next;
free(p);
return S;
}
创建有向图:
int LocateVex(ALGraph *G, VerTexType v)
{
int i;
for (i = 0; i < (G->vexnum); i++)
{
if (v == G->vertices[i].data)
return i;
}
}
void CreateUDG(ALGraph *G)
{
int i, j, k;
VerTexType v1, v2;
ArcNode *p1;
printf("输入总节点数和总边数:");
scanf("%d %d", &G->vexnum, &G->arcnum);
fflush(stdin);
printf("输入各个节点的值:");
for (i = 0; i < G->vexnum; i++)
{
scanf("%c", &G->vertices[i].data);
G->vertices[i].firstarc = NULL;
}
for (k = 0; k < G->arcnum; k++)
{
fflush(stdin);
printf("输入一条边的两个节点:");
scanf("%c %c", &v1, &v2);
i = LocateVex(G, v1);
j = LocateVex(G, v2);
p1 = (ArcNode *)malloc(sizeof(ArcNode));
p1->adjvex = j;
p1->nextarc = G->vertices[i].firstarc;
G->vertices[i].firstarc = p1;
indegree[j]++;
}
}
注意在创建图过程中记录节点的入度。
拓扑排序算法:
Status TopologicalSort(ALGraph G, int *topo)
{
int i, m, k;
StackList S;
ArcNode *p;
S = NULL;
for (i = 0; i < G.vexnum; i++)
{
if (!indegree[i])
S=Push(S, i);
}
m = 0;
while (S)
{
S=Pop(S, &i);
topo[m] = i;
++m;
p = G.vertices[i].firstarc;
while (p != NULL)
{
k = p->adjvex;
--indegree[k];
if (indegree[k] == 0)
S=Push(S, k);
p = p->nextarc;
}
}
topo[m] = -1;
if (m < G.vexnum)
return ERROR;
else
return OK;
}
先声明栈指针S,并让其指向NULL。检查所有节点中是否有入度为0的节点,如果有,则进栈。之后当栈不为空的时候,先出栈,取出栈顶元素,并将其记录在topo[]数组中;让指针p指向记录出栈节点的第一条边的节点,将这个节点出度指向的所有节点的记录入度的indegree[]减一,当某个indegree为0的时候,进栈。
当栈为空的时候让最后一个topo元素为-1(为什么需要这一步?因为原来数组我设置为0,而0号元素也有储存节点值,这样无法分辨是否已经结束。当然,也可以初始化的时候全部初始化为-1)。
最后检测topo[]数组中元素是否已经达到节点数,如果是,返回OK,达不到则返回ERROR,表示无法完全遍历。
加入main():
int main(void)
{
ALGraph G;
int i;
int topo[99] = {0};
CreateUDG(&G);
if (TopologicalSort(G, topo))
{
for (i = 0; topo[i] != -1; i++)
{
printf("%c ", G.vertices[topo[i]].data);
}
}
else
printf("错误");
printf("\n");
return 0;
}