C++图结构的图结构操作示例

示例代码:

/*
	By qianshou
	2013/10/5明天就要开学了~哎~
*/ 
#include<iostream>
using namespace std;
/*******************准备数据*****************************/
#define MaxNum 20					//图的最大顶点数
#define MaxValue 65535				//最大值 
struct GraphMatrix
{
	char Vertex[MaxNum];			//保存顶点信息(序号或字母)
	int GType;						//图的类型(0:无向图,1:有向图)
	int VertexNum;					//顶点的数量 
	int EdgeNum;					//边的数量
	int EdgeWeight[MaxNum][MaxNum]; //保存边的权值
	int IsTrav[MaxNum];				//遍历标志(用来标示是否被访问过) 
};
/******************创建图********************************/
void CreateGraph(GraphMatrix *GM)
{
	void ClearGraph(GraphMatrix *GM);	
	int i,j,k;
	int weight;						//权值
	char EstartV,EendV;				//边的起点和终点
	cout<<"请输入图的类型:0.表示无向图;1表示有向图:";
	cin>>GM->GType; 
	cout<<"请输入顶点的数量:";
	cin>>GM->VertexNum;
	cout<<"请输入图中的顶点信息:"<<endl;
	for(i=0;i<GM->VertexNum;i++)	//输入结点
	{
		cout<<"第"<<(i+1)<<"个顶点:";
		cin>>GM->Vertex[i];			//保存到顶点数组中 
	} 
	ClearGraph(GM);
	cout<<"请输入边的个数:"<<endl;
	cin>>GM->EdgeNum;	
	cout<<"输入每条边对应的起点,终点,以及权值:"<<endl;
	for(k=0;k<GM->EdgeNum;k++)
	{
		cout<<"第"<<k+1<<"条边:";
		cin>>EstartV>>EendV>>weight;
		for(i=0;GM->Vertex[i]!=EstartV;i++);	//在已有结点中查找起点
		for(j=0;GM->Vertex[j]!=EendV;j++);		//在已有结点中查找终点
		GM->EdgeWeight[i][j]= weight;			//在二维数组中保存对应的权值
		if(GM->GType==0)						//如果该图为无向图
		{
			GM->EdgeWeight[j][i]=weight;		//在对角位置保存权值 
		} 
	}
} 
/**********************清空图*************************************************/
void ClearGraph(GraphMatrix *GM)
{
	int i,j;
	for(i=0;i<GM->VertexNum;i++)
	{
		for(j=0;j<GM->VertexNum;j++)
		{
			GM->EdgeWeight[i][j]=MaxValue;		//使矩阵中的元素都为MaxValue	
		}
	}
} 
/**********************显示图(输出对应的邻接矩阵)*****************************/
void OutGraph(GraphMatrix *GM)
{
	int i,j;
	for(j=0;j<GM->VertexNum;j++)
	{
		cout<<"\t"<<GM->Vertex[j];				//在第一行输出结点信息 
	}
	cout<<endl;
	for(i=0;i<GM->VertexNum;i++)
	{
		cout<<GM->Vertex[i];
		for(j=0;j<GM->VertexNum;j++)
		{
			if(GM->EdgeWeight[i][j]==MaxValue)
			{
				cout<<"\t"<<'Z';				//输出Z表示无穷大 
			} 
			else
			{
				cout<<"\t"<<GM->EdgeWeight[i][j]; 
			}
		}
		cout<<endl; 
	}
} 
/***********************深度优先遍历算法***********************************/
void DeepTraOne(GraphMatrix *GM,int n)
{
	int i;
	GM->IsTrav[n]=1;				//表示该顶点已经处理过
	cout<<"->"<<GM->Vertex[n];		//输出标记过的顶点 
	//执行处理结点的操作
	for(i=0;i<GM->VertexNum;i++)
	{
		if(GM->EdgeWeight[n][i]!=MaxValue&&!GM->IsTrav[i])
		{
			DeepTraOne(GM,i);		//递归进行遍历 
		}
	} 
} 
void DeepTraGraph(GraphMatrix *GM)
{
	int i;
	for(i=0;i<GM->VertexNum;i++)	//清楚各顶点遍历标志 
	{
		GM->IsTrav[i]=0;	
	}
	cout<<"深度遍历结点:"<<endl;
	for(i=0;i<GM->VertexNum;i++)
	{
		if(!GM->IsTrav[i])			//若该顶点没有被访问过 
		{
			DeepTraOne(GM,i);		//调用函数遍历 
		}
	} 
	cout<<endl; 
}
/**********************主函数部分******************************************/
int main()
{
	GraphMatrix *GM;
	CreateGraph(GM);
	OutGraph(GM);
	DeepTraGraph(GM);
	return 0;
} 

程序运行结果:

实际的图结构应该是是这样的:


posted @ 2013-10-05 15:20  千手宇智波  阅读(693)  评论(0编辑  收藏  举报