数据结构c代码6:图的邻接矩阵表示及其存储

下面是用c语言实现的关于图的邻接矩阵表示及其存储代码:

#include
using namespace std;
/*使用邻接矩阵表示法创建无向图*/
/**
 * 1、输入总顶点数和总边数
 * 2、依次输入点的信息存入顶点表中
 * 3、初始化邻接矩阵,使每个权值初始化为极大值 
 * 4、构造邻接矩阵。依次输入每条边依附的顶点和其权值,确定两个顶点在图中的位置之后,使相应边 
 * 赋予相应的权值,同时使其对称边赋予相同的权值。 
 **/
/*图的邻接矩阵存储表示*/
#define MAXINT 32767      //表示的是极大值,即为无穷 
#define MVNum 100         //最大顶点数 
typedef char VerTexType;   //假设顶点的数据类型为字符类型 
typedef int ArcType;       //假设边的权值类型为整型
typedef struct AMGraph
{
	VerTexType vexs[MVNum];  //顶点数 
	ArcType arcs[MVNum][MVNum];  //邻接矩阵
	int vexnum, arcunm;     //图当前的点数和边数 
}AMGraph; 

int LocateVex(AMGraph G, char v)
{
	int index;
	for(int i=0;i<G.vexnum;i++)
	{
		if(v == G.vexs[i])
		{
			index = i;
			break;
		}
	}
	return index;
}

void Creat_UDN(AMGraph &G)
{
	char a, b;
	int w;
	cout<<"请输入图的总顶点数和边数:";
	cin>>G.vexnum>>G.arcunm;
	
	cout<<"\n请输入顶点"<<endl; 
	for(int i=0;i<G.vexnum;i++)
	{
		cin>>G.vexs[i];
	}
	
	for(int i=0;i<G.vexnum;i++)
	{
		for(int j=0;j<G.vexnum;j++)
		{
			if(i==j)
			{
				G.arcs[i][j] = 0;
			}
			else
			    G.arcs[i][j] = MAXINT;
		}
	}
	
	cout<<"\n";
	for(int i=0;i<G.arcunm;i++)
	{
		cout<<"请输入第"<<i+1<<"条边的信息(顶点 顶点 权值):" <<endl;
		cin>>a>>b>>w; 
		int m = LocateVex(G, a);
		int	n = LocateVex(G, b);
		G.arcs[m][n] = w;
		G.arcs[n][m] = G.arcs[m][n];
	}
}

void print_UDN(AMGraph G)
{
	cout<<"图的邻接矩阵如下:"<<endl;
	for(int i=0;i<G.vexnum;i++)
	{
		for(int j=0;j<G.vexnum;j++)
		{
			cout<<G.arcs[i][j]<<"  ";
		}
		cout<<"\n";
	}
}
int main()
{
	AMGraph G;
	Creat_UDN(G); 
	print_UDN(G);
	return 0;
} 

运行结果如下:
数据结构c代码6:图的邻接矩阵表示及其存储_第1张图片
有不懂的可以留言,如果这篇文章对你有帮助,请帮忙给个赞!!!!

你可能感兴趣的:(数据结构,数据结构,c语言,c++)