(3)重复上述两步,直到剩余的网中不再存在没有前趋的顶点为止.
打开IDE
我们创建一个工程
定义声明如下
#include "stdafx.h" //拓扑排序 #include<iostream> #include<iomanip> #include<stdlib.h> using namespace std; typedef struct {char w1,w2; float w; }RCW; typedef struct {char *data; int *visited; float **edge; int max,size; }Graph; //初始化图 void SetGraph(Graph *G,int n) {int i,j; G->data=new char[n]; G->visited=new int[n]; G->edge=(float **)malloc(n*sizeof(float *)); for(i=0;i<n;i++) G->edge[i]=(float *)malloc(n*sizeof(float)); for(i=0;i<n;i++) G->visited[i]=0; for(i=0;i<n;i++) for(j=0;j<n;j++) G->edge[i][j]=0; G->max=n; G->size=0; } //构造图 void MakeGraph(Graph *G,RCW r[],int n,int e) {int m=0; while(m<n) {if(G->size==G->max) {cout<<"Graph is full!\n"; exit(1);} G->data[G->size]='a'+m; G->size++;m++;} //插入弧 for(int p=0;p<e;p++) {int i,j,k; for(k=0;k<n;k++) {if(r[p].w1==G->data[k]) i=k; if(r[p].w2==G->data[k]) j=k;} G->edge[i][j]=r[p].w;} } typedef struct {int *data; int max,top; }Stack; void TopSort(Graph *G) {int i,j,n,d,count=0,*D; Stack S; if(G->size==0) return; n=G->size; S.data=new int[n]; S.max=n;S.top=-1; D=new int[n]; for(j=0;j<n;j++) {d=0; for(i=0;i<n;i++) if(G->edge[i][j]!=0) d++; D[j]=d; if(d==0) {if(S.top==S.max-1) {cout<<"Stack is full!\n";exit(1);} S.top++; S.data[S.top]=j; } } while(!(S.top==-1)) {if(S.top==-1) {cout<<"Pop an empty stack!\n";exit(1);} S.top--; i=S.data[S.top+1]; cout<<G->data[i]<<' '; count++; for(j=0;j<n;j++) if(G->edge[i][j]!=0) {D[j]--; if(D[j]==0) {if(S.top==S.max-1) {cout<<"Stack is full!\n";exit(1);} S.top++; S.data[S.top]=j; }}} if(count<n) cout<<"\nThere is a cycle."; free(D); free(S.data); }
调用如下
void main() {cout<<"运行结果:\n"; Graph G;int n=6,e=8;//n为顶点数,e为边数 RCW rcw[8]={{'a','b',1},{'a','d',1},{'a','e',1},{'b','f',1}, {'c','b',1},{'c','f',1},{'e','d',1},{'e','f',1}}; SetGraph(&G,n); MakeGraph(&G,rcw,n,e); TopSort(&G); free(G.data);//释放空间 free(G.visited); for(int i=0;i<G.max;i++) free(G.edge[i]); free(G.edge); cin.get(); }
效果如下
代码下载如下
http://download.csdn.net/detail/yincheng01/4789854