第十一周项目二

来源:互联网 发布:软件开发界面原则 编辑:程序博客网 时间:2024/05/29 17:07
  1. 烟台大学计算机学院  
  2.     
  3. 作者:王雪行 
  4.   
  5. 问题描述:假设图G采用邻接表存储,分别设计实现以下要求的算法:  
  6.   (1)输出出图G中每个顶点的出度;  
  7.   (2)求出图G中出度最大的一个顶点,输出该顶点编号;  
  8.   (3)计算图G中出度为0的顶点数;  
  9.   (4)判断图G中是否存在边<i,j> 
  10.   
  11. 输入描述:无 
  12.   
  13. 输出描述:输出验证结果 
  14.  
  15. 用到了算法库graph.h 
  16.   
  17. */   
  18.   
  19.   
  20.   
  21. #include <stdio.h>  
  22. #include <malloc.h>  
  23. #include "../graph.h"  
  24.   
  25. //返回图G中编号为v的顶点的出度  
  26. int OutDegree(ALGraph *G,int v)  
  27. {  
  28.     ArcNode *p;  
  29.     int n=0;  
  30.     p=G->adjlist[v].firstarc;  
  31.     while (p!=NULL)  
  32.     {  
  33.         n++;  
  34.         p=p->nextarc;  
  35.     }  
  36.     return n;  
  37. }  
  38.   
  39. //输出图G中每个顶点的出度  
  40. void OutDs(ALGraph *G)  
  41. {  
  42.     int i;  
  43.     for (i=0; i<G->n; i++)  
  44.         printf("  顶点%d:%d\n",i,OutDegree(G,i));  
  45. }  
  46.   
  47. //输出图G中出度最大的一个顶点  
  48. void OutMaxDs(ALGraph *G)  
  49. {  
  50.     int maxv=0,maxds=0,i,x;  
  51.     for (i=0; i<G->n; i++)  
  52.     {  
  53.         x=OutDegree(G,i);  
  54.         if (x>maxds)  
  55.         {  
  56.             maxds=x;  
  57.             maxv=i;  
  58.         }  
  59.     }  
  60.     printf("顶点%d,出度=%d\n",maxv,maxds);  
  61. }  
  62. //输出图G中出度为0的顶点数  
  63. void ZeroDs(ALGraph *G)  
  64. {  
  65.     int i,x;  
  66.     for (i=0; i<G->n; i++)  
  67.     {  
  68.         x=OutDegree(G,i);  
  69.         if (x==0)  
  70.             printf("%2d",i);  
  71.     }  
  72.     printf("\n");  
  73. }  
  74.   
  75. //返回图G中是否存在边<i,j>  
  76. bool Arc(ALGraph *G, int i,int j)  
  77. {  
  78.     ArcNode *p;  
  79.     bool found = false;  
  80.     p=G->adjlist[i].firstarc;  
  81.     while (p!=NULL)  
  82.     {  
  83.         if(p->adjvex==j)  
  84.         {  
  85.             found = true;  
  86.             break;  
  87.         }  
  88.         p=p->nextarc;  
  89.     }  
  90.     return found;  
  91. }  
  92.   
  93. int main()  
  94. {  
  95.     ALGraph *G;  
  96.     int A[7][7]=  
  97.     {  
  98.         {0,1,1,1,0,0,0},  
  99.         {0,0,0,0,1,0,0},  
  100.         {0,0,0,0,1,1,0},  
  101.         {0,0,0,0,0,0,1},  
  102.         {0,0,0,0,0,0,0},  
  103.         {0,0,0,1,1,0,1},  
  104.         {0,1,0,0,0,0,0}  
  105.     };  
  106.     ArrayToList(A[0], 7, G);  
  107.     printf("(1)各顶点出度:\n");  
  108.     OutDs(G);  
  109.     printf("(2)最大出度的顶点信息:");  
  110.     OutMaxDs(G);  
  111.     printf("(3)出度为0的顶点:");  
  112.     ZeroDs(G);  
  113.     printf("(4)边<2,6>存在吗?");  
  114.     if(Arc(G,2,6))  
  115.         printf("是\n");  
  116.     else  
  117.         printf("否\n");  
  118.     printf("\n");  
  119.     return 0;  
  120. }  


运行结果:

原创粉丝点击