图的转换

/*邻接矩阵定义*/
#define MAX_VERTERX_NUM 100
typedef char VertexType;
typedef int EdgeType;
typedef struct {
	VertexType vex[MAX_VERTERX_NUM];
	EdgeType arcs[MAX_VERTERX_NUM][MAX_VERTERX_NUM];
	int vexnum, arcnum;
} MGraph;

/*邻接表定义*/
#define MAX_VERTERX_NUM 100
typedef char VertexType;
typedef struct ArcNode {
	int adjvex;
	struct ArcNode *nextarc;
} ArcNode;
typedef struct VNode{
	VertexType data;
	ArcNode *firstarc;
} VNode, AdjList[MAX_VERTERX_NUM];
typedef struct {
	AdjList vertices;
	int vexnum, arcnum;
} ALGraph;

/*有向图的邻接表转邻接矩阵*/
void Convert(ALGraph G, MGraph &M) {
	M->vexnum = G.vexnum; //顶点数赋值
	M->arcnum = G.arcnum; //边数赋值
	ArcNode *p;
	for(int i=0; i<G.vexnum; i++) {//依次遍历各顶点表结点为头的边链表
		M->vex[i] = G.vertices[i].data; //顶点信息赋值
		for(p=G.vertices[i].firstarc; p; p=p->nextarc) {
			M->arcs[i][p->adjvex] = 1;
		}
	}
}

/*有向图的邻接矩阵转邻接表*/
void Convert(MGraph M, ALGraph &G) {
	G->vexnum = M.vexnum; //顶点数赋值
	G->arcnum = M.arcnum; //边数赋值
	ArcNode *p;
	for(int i=0; i<M.vexnum; i++) {
		G->vertices[i].data = M.vex[i]; //顶点信息赋值
		G->vertices[i].firstarc = NULL; //初始化firstarc指针
	}
	for(int i=0; i<M.vexnum; i++)
		for(int j=0; j<M.vexnum; j++)
			if(M.arcs[i][j]==1){
				p = new ArcNode;
				p->adjvex = j;
				p->nextarc = G->vertices[i].firstarc;
				G->vertices[i].firstarc = p;
			}
}

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值