有向图连接矩阵

图的定义

  1. #include <stdio.h>
  2. #define MAXVEX 100
  3. typedef char VertexType[3]; /*定义VertexType为char数组类型*/
  4. typedef struct vertex
  5. {
  6. int adjvex; /*顶点编号*/
  7. VertexType data; /*顶点的信息*/
  8. } VType; /*顶点类型*/
  9. typedef struct graph
  10. {
  11. int n,e; /*n为实际顶点数,e为实际边数*/
  12. VType vexs[MAXVEX]; /*顶点集合*/
  13. int edges[MAXVEX][MAXVEX]; /*边的集合*/
  14. } AdjMatix; /*图的邻接矩阵类型*/

创建图

  1. int CreateMatix(AdjMatix &g)
  2. {
  3. int i,j,k,b,t;
  4. int w;
  5. printf("顶点数(n)和边数(e):");
  6. scanf("%d%d",&g.n,&g.e);
  7. for (i=0;i<g.n;i++)
  8. {
  9. printf(" 序号为%d的顶点信息:",i);
  10. scanf("%s",g.vexs[i].data);
  11. g.vexs[i].adjvex=i; /*顶点编号为i*/
  12. }
  13. for (i=0;i<g.n;i++)
  14. for (j=0;j<g.n;j++)
  15. g.edges[i][j]=0;
  16. for (k=0;k<g.e;k++)
  17. {
  18. printf(" 序号为%d的边=>",k);
  19. printf(" 起点号 终点号 权值:");
  20. scanf("%d%d%d",&b,&t,&w);
  21. if (b<g.n && t<g.n && w>0)
  22. g.edges[b][t]=w;
  23. else
  24. {
  25. printf("输入错误!\n");
  26. return(0);
  27. }
  28. }
  29. return(1);
  30. }

列出图

  1. void DispMatix(AdjMatix g)
  2. {
  3. int i,j;
  4. printf("\n图的邻接矩阵:\n");
  5. for (i=0;i<g.n;i++)
  6. {
  7. for (j=0;j<g.n;j++)
  8. printf("%3d",g.edges[i][j]);
  9. printf("\n");
  10. }
  11. }

main

  1. void main()
  2. {
  3. AdjMatix g;
  4. CreateMatix(g);
  5. DispMatix(g);
  6. }