#include<stdio.h> #include<string.h> #include<stdlib.h> #define maxv 10 #define inf 32767 typedef char infotype; typedef struct { int no; infotype *info; } vertextype; typedef struct { int edges[maxv][maxv]; vertextype vexs[maxv]; int n; int e; } matgraph;

void creatematgraph(matgraph *&T, int n,int e) { e=0; T = (matgraph *)malloc(sizeof(matgraph));
infotype ch[10]; int k = 0, i = 0, j = 0; bool r; while (k < n) { scanf("%s", ch); T->vexs[k].no = k; T->vexs[k].info = new char[strlen(ch) + 1]; // 分配足够的内存 strcpy(T->vexs[k].info, ch); k++; } while (i < n) { j = 0; while (j < n) { printf("Is the edge [%d][%d] exist?\n", i, j); scanf("%d", &r); T->edges[i][j] = r; if(r!=0)e++; j++; } i++; } }

void printgraph(matgraph *&T, int n,int e) { int k = 0; while (k < n) { printf("No%d:%s\n", T->vexs[k].no, T->vexs[k].info); k++; } int i = 0, j = 0; while (i < n) { j = 0; while (j < n) { printf("%d ", T->edges[i][j]); j++; } printf("\n"); i++; } }

/*int main() {

matgraph *L;
int n = 3;
int e;
creatematgraph(L, n,e);
printgraph(L, n,e);
return 0;

}*/ matgraph.cpp 是一个为了创建和打印邻接矩阵图的程序。

该程序定义了一个结构&#x4F53matgraph,为了表示邻接矩阵图。其中包含了一个二维数&#x7EC4edges为了存储图的边,一个结构体数&#x7EC4vexs为了存储图的顶点信息,以及图的顶点数n和边数e。

程序中定义了两个函数creatematgraph和printgraph,分别为了创建邻接矩阵图和打印邻接矩阵图&#x3002

creatematgraph函数通过用户输入顶点信息和边的存在与否的信息来创建邻接矩阵图。首先通过循直输入顶点信息,然后通过层层循直输入边的存在与否的信息,并根据输入的值更新邻接矩阵和边数&#x3002

printgraph函数为了打印邻接矩阵图的顶点信息和邻接矩阵&#x3002

该程序的主函数部分被注释了,如果需要运行程序,可以取消注释后编译运行&#x3002

注意:该程序存在一些问题,如未检查再分配的成功与否的,以及未处理边数的正确计算&#x3002

C++ 邻接矩阵图实现: matgraph.cpp 代码解析

原文地址: https://www.cveoy.top/t/topic/qf7H 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录