逻辑结构分为两部分:V和E集合,其中,V是顶点,E是边。因此,用一个一维数组存放图中所有顶点数据;用一个二维数组存放顶点间关系(边或弧)的数据,这个二维数组称为邻接矩阵。
完整代码:
#include <iostream>
using namespace std;
#define Maxint 999
#define MVNum 100
//定义数据结构
typedef struct {
char vexs[MVNum]; //存放顶点的表
int arcs[MVNum][MVNum]; //邻接矩阵表
int vexnum,arcnum; //图的当前顶点数和边数
}AMGraph;
//在图中查找顶点
int LocateVex(AMGraph G, char u){
//在图G中查找顶点u,存在则返回顶点表中的下标,否则返回-1
for (int i = 0; i < G.vexnum; ++i) {
if (u == G.vexs[i])
return i;
}
return -1;
}
//创建无向网(带权图)
bool CreateUDN(AMGraph &G){
//对邻接矩阵初始化
cout<<"请依次输入顶点个数和边的个数:";
cin>>G.vexnum>>G.arcnum;
cout<<"请输入顶点:";
for (int i = 0; i < G.vexnum; ++i)
cin>>G.vexs[i];
for (int i = 0; i < G.vexnum; ++i) {
for (int j = 0; j < G.vexnum; ++j) {
G.arcs[i][j] = Maxint; //带权图:初始化权值为无穷大;无权图:初始化为0
}
}
//构造邻接矩阵
char v1,v2;
int w;
for (int k = 0; k < G.arcnum; ++k) {
cout<<"依次输入两个顶点和权值:";
cin>>v1>>v2>>w; //输入一条边所依附的顶点及边的权值
int i = LocateVex(G,v1);
int j = LocateVex(G,v2);
G.arcs[i][j] = w;
G.arcs[j][i] = w;
}
return true;
}
//输出邻接矩阵
void Show(AMGraph G){
cout<<"邻接矩阵如下:"<<endl;
cout<<" ";
for (int i = 0; i < G.vexnum; ++i) {
printf("%-5c",G.vexs[i]);
}
cout<<endl;
for (int i = 0; i < G.vexnum; ++i){
printf("%-5c",G.vexs[i]);
for (int j = 0; j < G.vexnum; ++j) {
printf("%-5d",G.arcs[i][j]);
}
putchar('\n');
}
}
int main() {
AMGraph G;
CreateUDN(G);
Show(G);
return 0;
}
运行结果展示:
针对下图所示的无向网进行测试