0.1) 本文总结于 数据结构与算法分析, 源代码均为原创, 旨在理解 拓扑排序的思想并用源代码加以实现;
0.2) 图论算法基础知识,参见 http://blog.csdn.net/pacosonswjtu/article/details/49893715
1.1)拓扑排序定义: 拓扑排序是对有向无圈图的顶点的一种排序, 它使得如果存在一条从 vi 到 vj的路径,那么在排序中 vj出现在 vi的后面;(有向无圈图:一个有向图没有圈, 圈:满足w1=wn 且长度至少为1个一条路径)
1.2)拓扑排序应用(有点像联机算法): 课程选修顺序, 如有向边(v, w)表明课程v 必须在课程w 选修前修完;(显然,如果图含有圈, 那么拓扑排序是不可能的)
1.3)一个简单的求拓扑排序的算法是: 先找出任意一个没有入边的顶点。 然后我们显示出该顶点,并将它和他的边一起从图中删除;
1.4)改进后的求拓扑排序的算法:
2.1)download source code:
https://github.com/pacosonTang/dataStructure-algorithmAnalysis/tree/master/chapter9/p219_topSort
2.2)source code at a glance(for full code, please download source code following the given link above):
#include "adjTable.h"
#include "queue.h"
void topSort(AdjTable* adj, int size, int* indegreeArray, Queue queue)
{
int i;
int counter;
ElementType vertex;
ElementType adjVertex;
AdjTable temp;
AdjTable temp1;
for(i=0; i<size; i++)
if(!indegreeArray[i]) // find the element who has zero indegree in adjoining table
enQueue(queue, i); //let the element enter the queue
printf("\t topSorting sequence is as follows: ");
counter = 0;
while(!isEmpty(queue))
{
vertex = deQueue(queue); // if the queue is empty, conducting departing queue
temp = adj[vertex]->next;
while(temp)
{
adjVertex = temp->index; // each adjVertex adjacent to vertex
if(--indegreeArray[adjVertex] == 0)
enQueue(queue, adjVertex);
temp1 = temp->next;
free(temp);
temp = temp1;
}
printf("vertex[%d] ", vertex+1);
counter++;
}
if(counter != size)
Error("failed top sorting, for graph has a cycle, from func topSort !");
disposeQueue(queue);
printf("\n\t");
}
// initializing indegree array with given size
int *initIndegree(int size)
{
int *indegreeArray;
int i;
indegreeArray = (int*)malloc(sizeof(int) * size);
if(!indegreeArray)
{
Error("failed intialization ,for out of space ,from func initIndegree");
return NULL;
}
for(i=0; i < size; i++)
indegreeArray[i] = 0;
return indegreeArray;
}
int main()
{
AdjTable* adj;
int *indegreeArray;
Queue queue;
int size = 7;
int i;
int j;
int column = 3;
int adjTable[7][3] =
{
{2, 4, 3},
{4, 5, 0},
{6, 0, 0},
{6, 7, 3},
{4, 7, 0},
{0, 0, 0},
{6, 0, 0}
};
printf("\n\n\t ====== test for topological sorting with adjoining table ======\n");
adj = initAdjTable(size);
indegreeArray = initIndegree(size);
queue = initQueue(size);
printf("\n\n\t ====== the initial adjoining table is as follows:======\n");
for(i = 0; i < size; i++)
for(j = 0; j < column; j++)
if(adjTable[i][j])
{
insertAdj(adj, adjTable[i][j]-1, i); // insertAdj the adjoining table over
indegreeArray[adjTable[i][j]-1]++; // update indegree of elements
}
printAdjTable(adj, size);
// topSorting starts
//void topSort(AdjTable* adj, int size, int* indegreeArray, Queue queue)
topSort(adj, size, indegreeArray, queue);
return 0;
}