An array of graphs (adjacency matrix) stores representations of # include <stdio.h> #include <stdlib.h> #define Max_vex_num 50typedef Char vertextype; typedef enum {DG, UDG} graphtype;typedef struct {vertextype vexs[max_vex_num]; int Arcs[max_vex_num][max_vex_num]; int Vexnum, arcnum; Graphtype type;} Mgraph; Position int Getindexofvexs (char vex, mgraph *mg) {int i; for (i = 1; I <= mg->vexnum; i++) {if (mg->vexs[i] = = vex) {return i; }} return 0;} Create diagram void create_mg (Mgraph *mg) {int I, j, K; int v1, v2, type; Char C1, C2; printf ("Please input graph type DG (0) or UDG (1):"); scanf ("%d", &type); if (type = = 0) Mg->type = DG; else if (type = = 1) mg->type = UDG; else {printf ("Please input correct graph type DG (0) or UDG (1)!"); Return } printf ("Please input Vexmun:"); scanf ("%d", &mg->vexnum); printf ("Please input arcnum:"); scanf ("%d", &mg->arcnum); GetChar (); For (i = 1; I <= mg->vexnum; i++) {printf ("Please input%dth vex (char):", I); scanf ("%c", &mg->vexs[i]); GetChar (); }//Initialize adjacency matrix for (i = 1; I <= mg->vexnum; i++) {for (j = 1; J <= mg->vexnum; J + +) { MG->ARCS[I][J] = 0; }}//input edge information, establish adjacency matrix for (k = 1; k <= mg->arcnum; k++) {printf ("Please input%dth Arc v1 (char) v2 (c HAR): ", K); scanf ("%c%c", &C1, &C2); V1 = Getindexofvexs (c1, MG); V2 = Getindexofvexs (c2, MG); if (Mg->type = = 1) mg->arcs[v1][v2] = mg->arcs[v2][v1] = 1; else mg->arcs[v1][v2] = 1; GetChar (); }}/** * Print adjacency matrix and vertex information */void print_mg (mgraph MG) {int I, J; if (Mg.type = = DG) {printf ("Graph type:direct graph:\n"); } else{printf ("Graph type:undirect graph:\n"); }printf ("Graph vertex number:%d \ n", mg.vexnum); printf ("Graph arc number:%d \ n", Mg.arcnum); printf ("Vertex set:"); for (i = 1; I <= mg.vexnum; i++) printf ("%c", Mg.vexs[i]);p rintf ("\ n"); printf ("adjacency matrix:\n"); for (i = 1; I <= mg.vexnum; i++) {j = 1; for (; J < Mg.vexnum; J + +) {printf ("%d", mg.arcs[i][j]); }printf ("%d", Mg.arcs[i][j]);p rintf ("\ n"); }} int main () {mgraph MG; CREATE_MG (&MG); PRINT_MG (MG); return 0;}
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Data structure---C-language implementation graph array (adjacency matrix) storage representation