【数据结构周周练】023 将图的邻接表表示转化为邻接矩阵表示的算法

47 篇文章 163 订阅
45 篇文章 26 订阅

一、图的存储结构

昨天给大家讲了图的存储结构,一共有四种,邻接表,邻接矩阵,十字链表以及邻接多重表,每个表都有自己的特色以及用途。

今天要给大家分享的是将一个用邻接表表示的图转为邻接矩阵表示,我们知道,邻接矩阵中,存储形式比较简单,普通的邻接矩阵只有0和1,0表示两个节点之间没有边,1表示有边。所以我们要遍历邻接表的每一个结点,得到它的边表,通过其next指针域获得与之相邻的所有边,并在矩阵中的对应位置赋值为1,剩余位置均赋值为0即可。

当然为了方便起见,我们将邻接矩阵的每个边初始化为0,在转化过程中,直接寻找存在的边,赋值为1即可。

二、代码

#define MaxVertexNum 100  //Maximum value of the vertex number
#define M 5

typedef char VertexType; //the type of vertex
typedef int EdgeType; // the type of wight on the edge in weighted graph 带权图中边上的权值的类型

// the graph are storaged by adjacency matrix 邻接矩阵存储图
typedef struct {
	VertexType Vex[MaxVertexNum]; //vertex list
	EdgeType Edge[MaxVertexNum][MaxVertexNum];  // adjacency matrix
	int vexNum, arcNum;  //current vertex number and arc of graph
}MGraph;

//the graph are storaged by adjacency list
typedef struct ArcNode {
	int adjvex;  // the location of the vertex which was pointed by arc
	struct ArcNode *next;
}ArcNode;

typedef struct VNode {
	VertexType data;
	ArcNode *first;
}VNode, AdjList[MaxVertexNum];

typedef struct {
	AdjList vertices;  // adjacency list
	int vexNum, arcNum;  // current vertex number and arc of graph
}*ALGraph;

void ConvertGraph(ALGraph &G, EdgeType Edge[M][M])
{
	for (int i = 0; i < G->vexNum; i++)
	{
		ArcNode *p = G->vertices[i].first;
		while (!p)
		{
			Edge[i][p->adjvex] = 1;
			p = p->next;
		}
	}
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值