无向无权图的邻接矩阵编程
//参考博客:https://blog.csdn.net/qq_54162207/article/details/117414707
#include <iostream>
using namespace std;
#define Maxsize 100
#define VertexmMaxNum 20
#define ERROR 0
#define OK 1
typedef string VertexType;
typedef int EdgeType;
typedef struct Graph //无向图
{
VertexType vex[VertexmMaxNum];
EdgeType edge[VertexmMaxNum][VertexmMaxNum];
int vexnum; //顶点数
int edgenum; //边数
}Graph;
//确定某顶点在G中的位置下标
int locateVex(Graph& G, VertexType v)
{
for (int i = 0; i < G.vexnum; i++)
{
if (v == G.vex[i]) return i;
}
return -1;
}
void CreateUG(Graph& G)
{
int i = 0, j = 0;
cout << "请输入无向图的顶点数和边数:";
cin >> G.vexnum >> G.edgenum;
cout << "请输入顶点:";
for (i = 0; i < G.vexnum; i++)
{
cin >> G.vex[i];
}
for (i = 0; i < G.vexnum; i++)
{
for (j = 0; j < G.vexnum; j++)
G.edge[i][j] = 0;
}
for (int k= 0; k < G.edgenum; k++)
{
cout << "请输入第"<<k+1<<"条边:";
VertexType v1, v2;
cin >> v1 >> v2;
int i = locateVex(G, v1);
int j = locateVex(G, v2);
G.edge[j][i]=G.edge[i][j] = 1;
}
}
/*--------打印图的邻接矩阵-----------*/
void PrintfUGraph(Graph G) {
//将图的邻接矩阵输出在控制台上
for (int i = 0; i < G.vexnum; i++) {
cout << "v" << i + 1 << ":";
for (int j = 0; j < G.vexnum; j++)
cout << G.edge[i][j] << " ";
cout << endl;
}
}
//顶点信息
//v1 v2 v3 v4 v5 v6 v7 v8
//边信息
/*
v1 v2
v1 v3
v2 v4
v2 v5
v3 v6
v3 v7
v4 v8
v5 v8
v6 v7
*/
int main(void)
{
Graph G;
CreateUG(G); //不带权无向图
PrintfUGraph(G);
return 0;
}