資料結構基礎:拓撲排序
對一個有向無環圖G進行拓撲排序,是將G中所有的頂點排成一個線性序列,使得圖中任意一對頂點u和v,若<u,v>屬於E(G),則u線上性序列中出現在v之前。
方法:
1. 在有向圖中選取一個沒有前驅的頂點輸出值
2. 從圖中刪除該頂點和所有以它為尾的弧
3. 重複上述過程,直到所有頂點均輸出
程式碼:
TopoSort.h
#ifndef TOPOSORT
#define TOPOSORT
#include< iostream>
#include< stack>
using namespace std;
#define Max_Vertex_Num 100
typedef struct Vnode{
VertexType data;
int in;
Arcnode *firstarc;
}Vnode,AdjList[Max_Vertex_Num];
typedef struct ArcNode{
int adjvex;
ArcNode *nextarc;
}ArcNode;
typedef struct{
AdjList vertices;
int vernum,arcnum;
}ALGraph;
#endif
Toposort.cpp
#include "TopoSort.h"
int TopoSort(ALGraph G){
int count =0;
ArcNode *p;
stack<int> s;
for(int i=0;i<G.vernum;i++){
if(G.vertices[i].in==0){
s.push(i);
}
}
while(!s.empty()){
int i = s.top();
s.pop();
p = G.vertices[i].firstarc;
while((count!=G.vernum)&&(p!=NULL)){
int indexver = p->adjvex;
G.vertices[indexver].in--;
if(G.vertices[indexver].in==0){
s.push(indexver);
count++;
}
p = p->nextarc;
}
}
if(count != G.vernum)
return 0;
return 1;
}