最新版的请看本博客图的三种存储方式。
#include <cstdio> #include <cstdlib> #include <cstring> #include <conio.h> #include <limits.h> #define MAXN 256 #define INFINITY INT_MAX #define MAX_VERTEX_NUM 20 #define OK 1 typedef int VRType; typedef int InfoType; typedef int VertexType; typedef int Status; typedef VRType AdjMatrix[MAX_VERTEX_NUM][MAX_VERTEX_NUM]; typedef VRType ArcCell; typedef int GraphKind; typedef struct{ VertexType vexs[MAX_VERTEX_NUM]; AdjMatrix arcs; int vexnum, arcnum; GraphKind kind; }MGraph; int LocateVex(MGraph *G, VertexType v){ int i; for(i=0; i<G->vexnum; i++) if(G->vexs[i] == v) return i; } Status CreateUDN(MGraph *G){ int i,j,k,v1,v2,w; scanf("%d %d", &G->vexnum, &G->arcnum); for(i=0; i<G->vexnum; i++) scanf("%d", &G->vexs[i]); for(i=0; i<G->vexnum; i++) for(j=0; j<G->vexnum; j++) G->arcs[i][j] = INFINITY; for(k=0; k<G->arcnum; k++){ scanf("%d %d %d", &v1, &v2, &w); i = LocateVex(G, v1); j = LocateVex(G, v2); G->arcs[i][j] = w; G->arcs[j][i] = G->arcs[i][j]; } return OK; } void print(MGraph *G){ int i,j; for(i=0; i<G->vexnum; i++){ for(j=0; j<G->vexnum; j++){ if(G->arcs[i][j] == INFINITY) printf("∞\t"); else printf("%d\t", G->arcs[i][j]); } putchar('\n'); } } int main(){ freopen("d:\\my.txt", "r", stdin); MGraph G; CreateUDN(&G); print(&G); return 0; }