对一个有向无环图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;
}