# 2. 算法原理与实现

## 入度表

• 找出图中0入度的顶点；
• 依次在图中删除这些顶点，删除后再找出0入度的顶点；
• 然后再删除……再找出……
• 直至删除所有顶点，即完成拓扑排序

// get in-degree array
int *getInDegree(Graph *g) {
int *inDegreeArray = (int *) malloc(g->V * sizeof(int));
memset(inDegreeArray, 0, g->V * sizeof(int));
int i;
for(i = 0; i < g->V; i++) {
while(pCrawl) {
inDegreeArray[pCrawl->dest]++;
pCrawl = pCrawl->next;
}
}
return inDegreeArray;
}

// topological sort function
void topologicalSort(Graph *g) {
int *inDegreeArray = getInDegree(g);
Stack *zeroInDegree = initStack();
int i;
for(i = 0; i < g->V; i++) {
if(inDegreeArray[i] == 0)
push(i, zeroInDegree);
}

printf("topological sorted order\n");
while(!isEmpty(zeroInDegree)) {
i = pop(zeroInDegree);
printf("vertex %d\n", i);

while(pCrawl) {
inDegreeArray[pCrawl->dest]--;
if(inDegreeArray[pCrawl->dest] == 0)
push(pCrawl->dest, zeroInDegree);
pCrawl = pCrawl->next;
}
}
}


## DFS

C实现：

/* recursive DFS function to traverse the graph,
* the graph is represented by adjacency list
*/
void dfs(int u, Graph *g, int *visit, Stack *s) {
visit[u] = 1;
while(pCrawl) {
if(!visit[pCrawl->dest])
dfs(pCrawl->dest, g, visit, s);
pCrawl = pCrawl->next;
}
push(u, s);
}

// the topological sort function
void topologicalSort(Graph *g) {
int *visit = (int *) malloc(g->V * sizeof(int));
memset(visit, 0, g->V * sizeof(int));
Stack *s = initStack();
int i;
for(i = 0; i < g->V; i++) {
if(!visit[i]) dfs(i, g, visit, s);
}

// the order of stack element is the sorted order
while(!isEmpty(s)) {
printf("vertex %d\n", pop(s));
}
}


# 3. 参考资料

[1] R. Rao, Lecture 20: Topo-Sort and Dijkstra’s Greedy Idea.
[2] GeeksforGeeks, Topological Sorting.
[3] GeeksforGeeks, Graph and its representations.

posted @ 2015-12-29 14:44  Treant  阅读(47473)  评论(0编辑  收藏  举报