图-邻接矩阵实现(c语言)

前期回顾:顺序表 链表 队列 二叉树的遍历

图的邻接矩阵

结构体:

//图结点 
typedef struct GNode {
	int Nv; 	//顶点点个数 
	int Ne; 	//边数 
	weightType G[MaxVertexNum][MaxVertexNum];
}GNode, *MGraph;

//边结点
typedef struct ENode {
	Vertex V1, V2;
	weightType Weight; 
}*Edge;

初始化图(图不可为空):

//初始化所顶点 
MGraph CreateGraph(int VertexNum)
{
	MGraph Graph;
	Vertex V,W; 
	
	Graph = (MGraph)malloc(sizeof(GNode));
	Graph->Nv = VertexNum;
	Graph->Ne = 0;
	for(V = 0;V < Graph->Nv;V++)
	for(W = 0;W < Graph->Nv;W++)
	Graph->G[V][W] = 0;
	return Graph;
}

插入边

//插入边
 void InsertEdge( MGraph Graph, Edge E)
 {
 	Graph->G[E->V1][E->V2] = E->Weight;
 	/*若是无向图则还要插入<V2,V1>*/
  //Graph[E->V2][E->V1]; = E->Weight;
 }

建图

 //建图 
 MGraph BuildGraph()
 {
 	MGraph Graph;
 	Edge E;
 	Vertex V;
 	int NV;
 	printf("请输入节点个数:\n");
 	scanf("%d",&(Graph->Nv));
 	Graph = CreateGraph(Graph->Nv);
 	printf("请输入边数:\n");
 	scanf("%d", &(Graph->Ne)); 
	 if(Graph->Ne !=0 ) {
	 	E = (Edge)malloc(sizeof(Edge));
	 	for(int i =0;i<Graph->Ne;i++){
	 		printf("输入v1编号、v2编号和权值:\n");
	 		scanf("%d %d %d",&(E->V1), &(E->V2),&(E->Weight));
	 		InsertEdge(Graph,E);
		 }
	 } 
	 return Graph;
 }

完整代码:

#include<stdio.h>
#include<malloc.h>

#define MaxVertexNum 100
typedef int weightType ;
typedef int Vertex;
//图结点 
typedef struct GNode {
	int Nv; 	//顶点点个数 
	int Ne; 	//边数 
	weightType G[MaxVertexNum][MaxVertexNum];
}GNode, *MGraph;

//边结点
typedef struct ENode {
	Vertex V1, V2;
	weightType Weight; 
}*Edge;


//初始化所顶点 
MGraph CreateGraph(int VertexNum)
{
	MGraph Graph;
	Vertex V,W; 
	
	Graph = (MGraph)malloc(sizeof(GNode));
	Graph->Nv = VertexNum;
	Graph->Ne = 0;
	for(V = 0;V < Graph->Nv;V++)
	for(W = 0;W < Graph->Nv;W++)
	Graph->G[V][W] = 0;
	return Graph;
}

//插入边
 void InsertEdge( MGraph Graph, Edge E)
 {
 	Graph->G[E->V1][E->V2] = E->Weight;
 	/*若是无向图则还要插入<V2,V1>*/
  //Graph[E->V2][E->V1]; = E->Weight;
 }
 
 //建图 
 MGraph BuildGraph()
 {
 	MGraph Graph;
 	Edge E;
 	Vertex V;
 	int NV;
 	printf("请输入节点个数:\n");
 	scanf("%d",&(Graph->Nv));
 	Graph = CreateGraph(Graph->Nv);
 	printf("请输入边数:\n");
 	scanf("%d", &(Graph->Ne)); 
	 if(Graph->Ne !=0 ) {
	 	E = (Edge)malloc(sizeof(Edge));
	 	for(int i =0;i<Graph->Ne;i++){
	 		printf("输入v1编号、v2编号和权值:\n");
	 		scanf("%d %d %d",&(E->V1), &(E->V2),&(E->Weight));
	 		InsertEdge(Graph,E);
		 }
	 } 
	 return Graph;
 }
 
int main()
{
	int Num;
	MGraph Graph;
	Graph = BuildGraph();
	Vertex V,W; 
//	for(V = 0;V < Graph->Nv;V++)
//	{ 
//	for(W = 0;W < Graph->Nv;W++) 
//	printf("%d ",Graph->G[V][W]); 
//	printf("\n"); 
//	} 
	return 0;
 } 
  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值