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     }
 65 }
 66 void PrintGragh(Graph &g)
 67 {
 68     //打印水平的表
 69     cout << "\t";
 70     for (int i = 0; i < g.vertexNum; i++)
 71     {
 72         cout << g.vertex[i] <<"\t";
 73     }
 74     //打印垂直表
 75     for (int i = 0; i < g.vertexNum; i++)
 76     {
 77         cout << endl;
 78         cout << g.vertex[i]<<"\t";
 79         for (int j = 0; j < g.vertexNum; j++)
 80         {
 81             if (g.edge[i][j] == 1)
 82             {
 83                 cout << "1" << "\t";
 84             }
 85             else
 86             {
 87                 cout << "0" << "\t";
 88             }
 89         }
 90     }
 91     cout << endl;
 92 
 93 }
 94 
 95 void test01()
 96 {
 97     Graph g;
 98     CreateGraph(g);
 99     PrintGragh(g);
100 }
101 int main()
102 {
103     test01();
104     return 0;
105 }