图的邻接矩阵实现:
Graph.h 文件:
#include<iostream.h>
#include"seqlist.h"
template<typename VertexType>class SeqList;
const int MaxVertexes= 20 ; //max vertexes
template<typename VertexType,typename ArcType>class Graph{
friend class SeqList<VertexType>;
private:
ArcType arcs[MaxVertexes][MaxVertexes];
SeqList<VertexType> vertexes; // vertexes sequence
int currentarcsize;
public:
Graph(){
for(int i=0;i<MaxVertexes;i++)
for(int j=0;j<MaxVertexes;j++)
arcs[i][j]=0;
}
int InsertVertexes(VertexType &v);
int InsertArc(int v1,int v2); //insert one border in num of vertexes v1 to v2
int Delete(int v1,int v2); //delete the border
int Delete(int v); //delete the vertex and the border
int GetVertexNum(){
return vertexes.GetLen();
}
void PrintGraphVertex(){
cout<<"the graph's vertexes is:"<<endl;
vertexes.Print();
}
void PrintGraphArc(){
int j,max=vertexes.GetLen();
cout<<"the grpah's arc is:"<<endl;
for(int i=0;i<max;i++){
for(j=0;j<max;j++)
cout<<arcs[i][j]<<" ";
cout<<endl;
}
}
};
template<typename VertexType,typename ArcType>int Graph<VertexType, ArcType>::InsertVertexes(VertexType &v){
return vertexes.Insert(v);
}
template<typename VertexType,typename ArcType>int Graph<VertexType, ArcType>::InsertArc(int v1,int v2){
if(v1<0 ||v1>vertexes.GetLen()-1||v2<0 ||v2>vertexes.GetLen()-1){
cout<<"the vertex is not exits:"<<endl;return 0;
}
arcs[v1][v2]=1;
currentarcsize++;
return 1;
}
主测试函数:
Main.cpp
Int main()
{
Graph<char,int> graph;
char a[3],&b=a[0];
int v1[4]={0,0,1,2},v2[4]={1,2,2,1};
for(int i=0;i<3;i++){
cin>>a[i];
b=a[i];
graph.InsertVertexes(b);
}
for(i=0;i<4;i++){
graph.InsertArc(v1[i],v2[i]);
}
//cout<<graph.InsertVertexes(b)<<endl;
graph.PrintGraphVertex(); cout<<endl;
//graph.PrintGraphArc();
//graph.InsertArc(0,0);
graph.PrintGraphArc();
return 0;
}