由于图中顶点间的关系(弧或边)无规律,故对图的存储较之表或树要复杂的多,需要根据图的具体应用来构造图的存储结构。
常用的存储表示有“数组表示法”、“邻接表”、“十字链表”和“邻接多重表”。
数组表示法
图的数组表示法又称“邻接矩阵”(Adjacency Matrix)表示法。 G = (V,R)
用两个数组来存储图G:
一个数组(一维)存储G中顶点集合V;另一个数组(二维)映像图中顶点间的关系集R,该二维数组就是所谓的邻接矩阵。该邻接矩阵是一个n阶方阵。
#include <stdio.h>
#include <stdlib.h>
#include <string.h> //memset
//#include <strings.h> //bzero
typedef struct _adjm_graph_{
void *relation;
int vn;
}MGraph;
MGraph *init_ajmgraph(int vn);
int free_adjmgraph(MGraph *graph);
int add_edge(MGraph *graph, int vx, int vy);
int show_adjmgraph(MGraph *graph);
int main()
{
MGraph *graph = NULL;
int v2, v1;
int vn = 0;
puts("input number of vertexes:");
while( 1 != scanf("%d", &vn))
getchar();
graph = init_ajmgraph(vn);
#if 1
puts("input the relation of vertexes:");
while(1)
{
while( 2 != scanf("%d%d", &v1, &v2))
getchar();
if(v1 == v2)
break;
add_edge(graph, v1, v2);
}
show_adjmgraph(graph);
#endif
free_adjmgraph(graph);
return 0;
}
MGraph *init_ajmgraph(int vn)
{
MGraph *graph = NULL;
graph = (MGraph *)malloc(sizeof(MGraph));
graph->relation = malloc(vn * vn);
memset(graph->relation, 0, vn * vn);
// bzero(graph->relation, vn * vn);
graph->vn = vn;
return graph;
}
int free_adjmgraph(MGraph *graph)
{
free(graph->relation);
free(graph);
return 0;
}
int add_edge(MGraph *graph, int vx, int vy)
{
char (*relation)[graph->vn] = graph->relation;
if(vx < 0 || vy < 0 || vx >= graph->vn || vy >= graph->vn)
return -1;
relation[vx][vy] = 1; //GNU C
// p[vx * graph->vn + vy] = 1; //ISO C90
}
int show_adjmgraph(MGraph *graph)
{
int i,j;
int vn = graph->vn;
char (*relation)[vn] = graph->relation;
for(i = 0; i < vn; i ++)
{
printf("v%d: ", i);
for(j = 0; j < vn; j ++)
{
if(relation[i][j] == 1)
printf(" v%d,", j);
}
puts("\b ");
}
}