图的存储结构之数组表示法

        由于图中顶点间的关系(弧或边)无规律,故对图的存储较之表或树要复杂的多,需要根据图的具体应用来构造图的存储结构。

常用的存储表示有“数组表示法”、“邻接表”、“十字链表”和“邻接多重表”。

 

数组表示法

图的数组表示法又称“邻接矩阵”(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 ");
	}
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值