Catalog
2. Adjacency matrix representation of undirected graph
3. Adjacency matrix representation of Digraphs
4. Adjacency matrix representation of networks
1. adjacency matrix
(1) storing vertex information with one-dimensional array
(2) using matrix (two-dimensional array) to represent vertex adjacency in graph
2. Adjacency matrix representation of undirected graph
Rule: if two nodes are connected, set 1 at the corresponding position element of the matrix, otherwise set 0
3. Adjacency matrix representation of Digraphs
Rule: if two nodes are connected, the corresponding position element of the matrix is the weight on the edge, otherwise it is infinite
4. Adjacency matrix representation of networks
Rule: if two nodes are connected, the corresponding position element of the matrix is the weight on the edge, otherwise it is infinite
5. Sample source code (take the undirected graph above as an example)
#include <stdio.h> #include <stdlib.h> #Define max? Vertex? Num 100 / * maximum number of nodes in the graph*/ typedef char VertexType; /* Vertex type set to character */ typedef int EdgeType; /* Edge weight type set to integer */ typedef struct /* Edge table node */ { VertexType vex[MAX_VERTEX_NUM]; /* Vertex table */ EdgeType edges[MAX_VERTEX_NUM][MAX_VERTEX_NUM]; /* adjacency matrix */ int vexnum; /* Number of nodes */ int edgenum; /* Number of edges */ }MGraph; void CreateMG(MGraph * MG); /* Adjacency table method to create undirected graph */ void PrintMG(MGraph MG); /* Adjacency matrix form output graph MG */ int main(void) { MGraph g; CreateMG(&g); printf("------------------------------\n"); printf("vexnum = %d ; edgenum = %d\n", g.vexnum, g.edgenum); printf("------------------------------\n"); PrintMG(g); return 0; } void CreateMG(MGraph * MG) { int i = 0, j, k, w; /* w: Weight */ char ch; printf("Please input the number of top points and sides in order:"); scanf("%d %d", &(MG->vexnum), &(MG->edgenum)); printf("Please enter vertices in turn (end with enter):"); getchar(); while ((ch = getchar()) != '\n') /* Enter vertex information */ MG->vex[i++] = ch; /* Another way to enter vertex information for (i = 0; i < MG->vexnum; i++) scanf("\n%c", &(MG->vex[i])); */ for (i = 0; i < MG->vexnum; i++) /* Initialize adjacency matrix */ for (j = 0; j < MG->vexnum; j++) MG->edges[i][j] = 0; printf("vertex | subscript\n"); for (i = 0; i < MG->vexnum; i++) /* Display the vertex and its corresponding subscript in the graph */ { printf("%3c%6d\n", MG->vex[i], i); } printf("Please enter two vertex serial numbers corresponding to each table (Format: i,j): \n"); for (k = 0; k < MG->edgenum; k++) /* Adjacency Matrix Building */ { scanf("\n%d,%d", &i, &j); MG->edges[i][j] = 1; MG->edges[j][i] = 1; } } void PrintMG(MGraph MG) { int i, j; for (i = 0; i < MG.vexnum; i++) /* Output adjacency matrix */ { for (j = 0; j < MG.vexnum; j++) printf("%2d", MG.edges[i][j]); printf("\n"); } }