您的位置:首页 > 编程语言 > C语言/C++

图的邻接矩阵表示的C++类实现

2016-06-05 15:41 323 查看
任何的抽象数据类型(Abstract Data Type)都由3要素组成,名称、数据对象集合操作集。对于图的数据结构,其名称为Graph(图),数据对象集由一个非空的有限顶点集合和一个有限边集合组成,操作集包括插入顶点、插入边等。教材上对于图的实现形式主要介绍了两种:邻接矩阵和邻接表,本文采用临街矩阵的表示图,初步实现简单的图类,可以进行创建图、插入边、打印图等操作。

//graphadjcencymatrix.h
#ifndef GRAPHADJCENCYMATRIX
#define GRAPHADJCENCYMATRIX
#include <IOSTREAM>
const int MaxVertexNum=100;
typedef int Vertex;
typedef int Weight;
typedef char DataType;
struct Edge
{
Vertex v1;
Vertex v2;
Weight w;
};
class GraphAdjMat
{
private:
int VertexNum;
int EdgeNum;
int Weight[MaxVertexNum][MaxVertexNum];
DataType Data[MaxVertexNum];
public:
GraphAdjMat();
~GraphAdjMat(){}
void InsertEdge(Edge);
void BuildGraph();
void Print();
};
GraphAdjMat::GraphAdjMat()
{
VertexNum=0;
EdgeNum=0;
for(int i=0;i<MaxVertexNum;i++)
{
Data[i]='*';
for(int j=0;j<MaxVertexNum;j++)
{
Weight[i][j]=-1;
}
}
}
void GraphAdjMat::InsertEdge(Edge temp)
{
//EdgeNum++;
Weight[temp.v1-1][temp.v2-1]=temp.w;
}
void GraphAdjMat::BuildGraph()
{
std::cout<<"Please input the vertex count:\n";
std::cin>>VertexNum;
std::cout<<"Please input the edge count:\n";
std::cin>>EdgeNum;
std::cout<<"Please input the vertices and weight of the edge:\n";
for(int i=0;i<EdgeNum;i++)
{
int a,b,c;
std::cin>>a>>b>>c;
Edge first={a,b,c};
InsertEdge(first);
}
}
void GraphAdjMat::Print()
{
int i,j;
for(i=0;i<VertexNum;i++)
std::cout<<Data[i]<<" ";
std::cout<<std::endl;
for(i=0;i<VertexNum;i++)
{
for(j=0;j<VertexNum;j++)
{
std::cout<<Weight[i][j]<<" ";
}
std::cout<<std::endl;
}
}
#endif
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  邻接矩阵 C++