第十三周 项目5拓扑排序

来源:互联网 发布:淘宝开店卖红酒 编辑:程序博客网 时间:2024/05/21 01:53
  1. /* 
  2. Copyright (c)2016,烟台大学计算机与控制工程学院 
  3. All rights reserved. 
  4. 文件名称:图(2).cpp 
  5. 作    者:   陈朋 
  6. 完成日期:2016年12月2日 
  7. 版 本 号:v1.0 
  8. 问题描述: 
  9. 输入描述:无 
  10. 程序输出:若干 
  11. */  
  12. #include <stdio.h>  
  13. #include <malloc.h>  
  14. #include "graph.h"  
  15.   
  16. void TopSort(ALGraph *G)  
  17. {  
  18.     int i,j;  
  19.     int St[MAXV],top=-1;            //栈St的指针为top  
  20.     ArcNode *p;  
  21.     for (i=0; i<G->n; i++)          //入度置初值0  
  22.         G->adjlist[i].count=0;  
  23.     for (i=0; i<G->n; i++)          //求所有顶点的入度  
  24.     {  
  25.         p=G->adjlist[i].firstarc;  
  26.         while (p!=NULL)  
  27.         {  
  28.             G->adjlist[p->adjvex].count++;  
  29.             p=p->nextarc;  
  30.         }  
  31.     }  
  32.     for (i=0; i<G->n; i++)  
  33.         if (G->adjlist[i].count==0)  //入度为0的顶点进栈  
  34.         {  
  35.             top++;  
  36.             St[top]=i;  
  37.         }  
  38.     while (top>-1)                  //栈不为空时循环  
  39.     {  
  40.         i=St[top];  
  41.         top--;              //出栈  
  42.         printf("%d ",i);            //输出顶点  
  43.         p=G->adjlist[i].firstarc;   //找第一个相邻顶点  
  44.         while (p!=NULL)  
  45.         {  
  46.             j=p->adjvex;  
  47.             G->adjlist[j].count--;  
  48.             if (G->adjlist[j].count==0)//入度为0的相邻顶点进栈  
  49.             {  
  50.                 top++;  
  51.                 St[top]=j;  
  52.             }  
  53.             p=p->nextarc;       //找下一个相邻顶点  
  54.         }  
  55.     }  
  56. }  
  57.   
  58. int main()  
  59. {  
  60.     ALGraph *G;  
  61.     int A[7][7]=  
  62.     {  
  63.         {0,0,1,0,0,0,0},  
  64.         {0,0,0,1,1,0,1},  
  65.         {0,0,0,1,0,0,0},  
  66.         {0,0,0,0,1,1,0},  
  67.         {0,0,0,0,0,0,0},  
  68.         {0,0,0,0,0,0,0},  
  69.         {0,0,0,0,0,1,0}  
  70.     };  
  71.     ArrayToList(A[0], 7, G);  
  72.     DispAdj(G);  
  73.     printf("\n");  
  74.     printf("拓扑序列:");  
  75.     TopSort(G);  
  76.     printf("\n");  
  77.     return 0;  

0 0
原创粉丝点击