拓扑排序算法
#include <stdio.h>
#include <malloc.h>
#include <string.h>
#define MAXVEX 100
typedef char VertexType[3];
typedef struct vertex
{
int adjvex;
VertexType data;
} VType;
typedef struct graph
{
int n,e;
VType vexs[MAXVEX];
int edges[MAXVEX][MAXVEX];
} AdjMatix;
typedef struct edgenode
{
int adjvex;
int value;
struct edgenode *next;
} ArcNode;
typedef struct vexnode
{
VertexType data;
int count;
ArcNode *firstarc;
} VHeadNode;
typedef struct
{
int n,e;
VHeadNode adjlist[MAXVEX];
} AdjList;
void DispAdjList(AdjList *G)
{
int i;
ArcNode *p;
printf("图的邻接表表示如下:\n");
for (i=0;i<G->n;i++)
{
printf(" [%d,%3s:]=>",i,G->adjlist[i].data,G->adjlist[i].count);
p=G->adjlist[i].firstarc;
while (p!=NULL)
{
printf("(%d,%d)->",p->adjvex,p->value);
p=p->next;
}
printf("∧\n");
}
}
void MatToList(AdjMatix g,AdjList *&G)
{
int i,j;
ArcNode *p;
G=(AdjList *)malloc(sizeof(AdjList));
for (i=0;i<g.n;i++)
{
G->adjlist[i].firstarc=NULL;
strcpy(G->adjlist[i].data,g.vexs[i].data);
}
for (i=0;i<g.n;i++)
for (j=g.n-1;j>=0;j--)
if (g.edges[i][j]!=0)
{
p=(ArcNode *)malloc(sizeof(ArcNode));
p->value=g.edges[i][j];p->adjvex=j;
p->next=G->adjlist[i].firstarc;
G->adjlist[i].firstarc=p;
}
G->n=g.n;G->e=g.e;
}
void TopSort(AdjList *G)
{
int i,j;
int St[MAXV],top=-1;
ArcNode *p;
for (i=0;i<n;i++)
if (adj[i].count==0)
{
top++;
St[top]=i;
}
while (top>-1)
{
i=St[top];top--;
printf("%d ",i);
p=adj[i].firstarc;
while (p!=NULL)
{
j=p->adjvex;
adj[j].count--;
if (adj[j].count==0)
{
top++;
St[top]=j;
}
p=p->nextarc;
}
}
}
void main()
{
int i,j;
AdjMatix g;
AdjList *G;
int a[6][6]={ {0,1,0,10},{1,0,1,0,0},{0,1,0,1,1},{1,0,1,0,1},{0,0,1,1,0} };
char *vname[MAXVEX]={"a","b","c","d","e"};
g.n=5;g.e=12;
for (i=0;i<g.n;i++)
strcpy(g.vexs[i].data,vname[i]);
for (i=0;i<g.n;i++)
for (j=0;j<g.n;j++)
g.edges[i][j]=a[i][j];
MatToList(g,G);
DispAdjList(G);
for (i=0;i<g.n;i++) visited[i]=0;
printf("从顶点0的深度优先遍历序列:\n");
printf(" 递归算法:");DFS(G,0);printf("\n");
for (i=0;i<g.n;i++) visited[i]=0;
printf(" 非递归算法:");DFS1(G,0);printf("\n");
}