完善下列代码,要求:实现基于邻接矩阵的新顶点的增加,不包含main函数。代码如下: #include<iostream> #define OK 1 #define ERROR 0 #define OVERFLOW -2 #define MVNum 100 using namespace std; typedef struct { int vexs[MVNum]; int arcs[MVNum][MVNum]; int vexnum,arcnum; }AMGragh; int CreateUDN(AMGragh &G,int vexnum,int arcnum) {} int InsertVex(AMGragh &G){ } int OutputUDN(AMGragh G) {}
时间: 2024-03-09 15:48:10 浏览: 108
下面是完善后的代码:
```c++
#include<iostream>
#define OK 1
#define ERROR 0
#define OVERFLOW -2
#define MVNum 100
using namespace std;
typedef struct {
int vexs[MVNum];
int arcs[MVNum][MVNum];
int vexnum, arcnum;
} AMGragh;
// 创建无向网
int CreateUDN(AMGragh &G, int vexnum, int arcnum) {
G.vexnum = vexnum;
G.arcnum = arcnum;
for (int i = 0; i < G.vexnum; i++) {
for (int j = 0; j < G.vexnum; j++) {
G.arcs[i][j] = INT_MAX; // 初始化为无穷大
}
}
for (int i = 0; i < G.vexnum; i++) {
cin >> G.vexs[i];
}
int v1, v2, weight;
for (int k = 0; k < G.arcnum; k++) {
cin >> v1 >> v2 >> weight;
G.arcs[v1][v2] = weight;
G.arcs[v2][v1] = weight;
}
return OK;
}
// 增加新顶点
int InsertVex(AMGragh &G) {
if (G.vexnum == MVNum) {
return ERROR; // 顶点数已满,无法添加
}
int newVex;
cout << "请输入新顶点的值:";
cin >> newVex;
G.vexs[G.vexnum] = newVex;
for (int i = 0; i < G.vexnum; i++) {
G.arcs[i][G.vexnum] = INT_MAX;
G.arcs[G.vexnum][i] = INT_MAX;
}
G.vexnum++;
return OK;
}
// 输出无向网
int OutputUDN(AMGragh G) {
cout << "输出无向网:" << endl;
for (int i = 0; i < G.vexnum; i++) {
for (int j = 0; j < G.vexnum; j++) {
if (G.arcs[i][j] == INT_MAX) {
cout << "∞" << "\t";
} else {
cout << G.arcs[i][j] << "\t";
}
}
cout << endl;
}
return OK;
}
```
其中,InsertVex函数用于增加新顶点,实现方式是在邻接矩阵中增加一行和一列,初始化为无穷大。同时,将新顶点的值存入G.vexs数组中,最后将G.vexnum加1即可。
注意,需要在程序开头添加`#include<climits>`头文件,以使用INT_MAX常量。
阅读全文