其他分享
首页 > 其他分享> > 无向图邻接矩阵代码实现

无向图邻接矩阵代码实现

作者:互联网

  1 //无向图邻接矩阵代码实现
  2 
  3 #include<iostream>
  4 using namespace std;
  5 #define MaxVertex 50    //最多顶点个数
  6 typedef char VertexInfo[9];//定义顶点的名字
  7 //定义图的数据结构
  8 struct Graph
  9 {
 10     //顶点数组
 11     VertexInfo vertex[MaxVertex];
 12 
 13     //顶点的边的数组
 14     int edge[MaxVertex][MaxVertex];
 15 
 16     //顶点的个数
 17     int vertexNum;
 18 
 19     //边的个数
 20     int edgeNum;
 21 };
 22 //获得用户输入的顶点在顶点数组中的位置
 23 int LocalVertext(Graph &a,VertexInfo V)
 24 {
 25     for (int i = 0; i < a.vertexNum; i++)
 26     {
 27         if (!strcmp(V, a.vertex[i]))
 28         {
 29             //如果找到了就返回1
 30             return i;
 31         }
 32     }
 33     //没有找到就返回-1
 34     return -1;
 35 }
 36 void CreateGraph(Graph &a)
 37 {
 38     cout << "请输入图的顶点数和边数:顶点 边" << endl;
 39     cin >> a.vertexNum >> a.edgeNum;
 40     //给每个顶点名字赋值
 41     cout << "请输入" << a.vertexNum << "个顶点的名字" << endl;
 42     for (int i = 0; i < a.vertexNum; i++)
 43     {
 44         cin >> a.vertex[i];
 45     }
 46     //初始化邻接矩阵
 47     for (int i = 0; i < a.vertexNum; i++)
 48     {
 49         for (int j = 0; j < a.vertexNum; j++)
 50         {
 51             a.edge[i][j] = 0;
 52         }
 53     }
 54     //给边的矩阵赋值
 55     VertexInfo v1, v2;
 56     int temp1,temp2;
 57     for (int i = 0; i < a.edgeNum; i++)
 58     {
 59         cout << "请输入想要给那两点添加边:v1 v2" << endl;
 60         cin >> v1 >> v2;
 61         temp1 = LocalVertext(a, v1);
 62         temp2 = LocalVertext(a, v2);
 63         a.edge[temp1][temp2] = 1;
 64         a.edge[temp2][temp1] = 1;
 65     }
 66 }
 67 void PrintGragh(Graph &g)
 68 {
 69     //打印水平的表
 70     cout << "\t";
 71     for (int i = 0; i < g.vertexNum; i++)
 72     {
 73         cout << g.vertex[i] <<"\t";
 74     }
 75     //打印垂直表
 76     for (int i = 0; i < g.vertexNum; i++)
 77     {
 78         cout << endl;
 79         cout << g.vertex[i]<<"\t";
 80         for (int j = 0; j < g.vertexNum; j++)
 81         {
 82             if (g.edge[i][j] == 1)
 83             {
 84                 cout << "1" << "\t";
 85             }
 86             else
 87             {
 88                 cout << "0" << "\t";
 89             }
 90         }
 91     }
 92     cout << endl;
 93 
 94 }
 95 
 96 void test01()
 97 {
 98     Graph g;
 99     CreateGraph(g);
100     PrintGragh(g);
101 }
102 int main()
103 {
104     test01();
105     return 0;
106 }

 

标签:cout,int,代码,vertexNum,邻接矩阵,temp2,temp1,无向,顶点
来源: https://www.cnblogs.com/Sna1lGo/p/14348948.html