/*
*Copyright(c) 2015, 烟台大学计算机学院
*All rights reserved.
*文件名称:拓扑排序算法验证.cpp
*作 者:周洁
*完成日期:2015年 11月27日
*版 本 号:
*
*问题描述:拓扑排序算法验证
*输入描述:若干数据
*输出描述:若干数据
*/
代码:
(1)头文件:图基本算法库
(2)源文件:
#include <stdio.h> #include <malloc.h> #include "graph.h" void ArrayToMat(int *Arr, int n, MGraph &g) { int i,j,count=0; //count用于统计边数,即矩阵中非0元素个数 g.n=n; for (i=0; i<g.n; i++) for (j=0; j<g.n; j++) { g.edges[i][j]=Arr[i*n+j]; //将Arr看作n×n的二维数组,Arr[i*n+j]即是Arr[i][j],计算存储位置的功夫在此应用 if(g.edges[i][j]!=0 && g.edges[i][j]!=INF) count++; } g.e=count; } void ArrayToList(int *Arr, int n, ALGraph *&G) { int i,j,count=0; //count用于统计边数,即矩阵中非0元素个数 ArcNode *p; G=(ALGraph *)malloc(sizeof(ALGraph)); G->n=n; for (i=0; i<n; i++) //给邻接表中所有头节点的指针域置初值 G->adjlist[i].firstarc=NULL; for (i=0; i<n; i++) //检查邻接矩阵中每个元素 for (j=n-1; j>=0; j--) if (Arr[i*n+j]!=0) //存在一条边,将Arr看作n×n的二维数组,Arr[i*n+j]即是Arr[i][j] { p=(ArcNode *)malloc(sizeof(ArcNode)); //创建一个节点*p p->adjvex=j; p->info=Arr[i*n+j]; p->nextarc=G->adjlist[i].firstarc; //采用头插法插入*p G->adjlist[i].firstarc=p; } G->e=count; } void DispAdj(ALGraph *G) //输出邻接表G { int i; ArcNode *p; for (i=0; i<G->n; i++) { p=G->adjlist[i].firstarc; printf("%3d: ",i); while (p!=NULL) { printf("-->%d/%d ",p->adjvex,p->info); p=p->nextarc; } printf("\n"); } } void TopSort(ALGraph *G) { int i,j; int St[MAXV],top=-1; //栈St的指针为top ArcNode *p; for (i=0; i<G->n; i++) //入度置初值0 G->adjlist[i].count=0; for (i=0; i<G->n; i++) //求所有顶点的入度 { p=G->adjlist[i].firstarc; while (p!=NULL) { G->adjlist[p->adjvex].count++; p=p->nextarc; } } for (i=0; i<G->n; i++) if (G->adjlist[i].count==0) //入度为0的顶点进栈 { top++; St[top]=i; } while (top>-1) //栈不为空时循环 { i=St[top]; top--; //出栈 printf("%d ",i); //输出顶点 p=G->adjlist[i].firstarc; //找第一个相邻顶点 while (p!=NULL) { j=p->adjvex; G->adjlist[j].count--; if (G->adjlist[j].count==0)//入度为0的相邻顶点进栈 { top++; St[top]=j; } p=p->nextarc; //找下一个相邻顶点 } } } int main() { ALGraph *G; int A[7][7]= { {0,0,1,0,0,0,0}, {0,0,0,1,1,0,1}, {0,0,0,1,0,0,0}, {0,0,0,0,1,1,0}, {0,0,0,0,0,0,0}, {0,0,0,0,0,0,0}, {0,0,0,0,0,1,0} }; ArrayToList(A[0], 7, G); DispAdj(G); printf("\n"); printf("拓扑序列:"); TopSort(G); printf("\n"); return 0; }
运行结果: