# 邻接矩阵

//图邻矩阵
#include<iostream>
using namespace std;
#define SIZE 10
class Graph
{
public:
Graph()
{
MaxVertex = SIZE;
NumVertex = NumEdge = 0;
Vertex = new char[MaxVertex];
Edge = new int*[MaxVertex];//int *Edge[10];
int i,j;
for(i = 0;i<MaxVertex;i++)
Edge[i] = new int[MaxVertex]; //Edge[10][10]
for(i = 0;i<MaxVertex;i++)
{
for(j = 0;j<MaxVertex;j++)
Edge[i][j] = 0;
}
}
void InsertVertex(char v)//插入顶点
{
if(NumVertex >= MaxVertex)
return;
Vertex[NumVertex++] = v;
}
int GetVertexI(char v)//获得顶点下标
{
int i;
for(i = 0;i<NumVertex;i++)
{
if(Vertex[i] == v)
return i;
}
return -1;
}
void InsertEdge(char v1,char v2)//插入边
{
int p1 = GetVertexI(v1);
int p2 = GetVertexI(v2);
if(p1 == -1 || p2 == -1)
return;
Edge[p1][p2] = Edge[p2][p1] = 1;
NumEdge++;
}
void ShowGraph()//显示邻接矩阵
{
int i,j;
cout<<"  ";
for(i = 0;i<NumVertex;i++)
cout<<Vertex[i]<<" ";
cout<<endl;
for(i = 0;i<NumVertex;i++)
{
cout<<Vertex[i]<<" ";
for(j = 0;j<NumVertex;j++)
cout<<Edge[i][j]<<" ";
cout<<endl;
}
}
//a b c d e
int GetEdgeNum(char v)//获得边的数目
{
int p = GetVertexI(v);
if(p == -1)
return 0;
int n = 0;
for(int i = 0;i<NumVertex;i++)
{
if(Edge[p][i] == 1)
n++;
}
return n;
}
void DeleteVertex(char v)//删除顶点
{
int p = GetVertexI(v);
if(p == -1)
return;
int i,j;
int temp = GetEdgeNum(v);
for(i = p;i<NumVertex-1;i++)  //顶点先删除
Vertex[i] = Vertex[i+1];

for(i = p;i<NumVertex-1;i++)  //行上移
{
for(j = 0;j<NumVertex;j++)
Edge[i][j] = Edge[i+1][j];
}
for(i = 0;i<NumVertex-1;i++)  //列左移
{
for(j = p;j<NumVertex-1;j++)
{
Edge[i][j] = Edge[i][j+1];
}
}

NumVertex--;
NumEdge-=temp;

}
void DeleteEdge(char v1,char v2)//删除边
{
int p1 = GetVertexI(v1);
int p2 = GetVertexI(v2);
if(p1 == -1 || p2 == -1)
return;
if(Edge[p1][p2] == 0)
return;
Edge[p1][p2] = Edge[p2][p1] = 0;
NumEdge--;
}
~Graph()//析构函数释放空间
{
delete []Vertex;
Vertex = NULL;
for(int i = 0;i<NumVertex;i++)
{
delete []Edge[i];
Edge[i] = NULL;
}
delete []Edge;
Edge = NULL;
MaxVertex = NumVertex = NumEdge = 0;
}
private:
int MaxVertex;
int NumVertex;
int NumEdge;
char *Vertex;
int **Edge;
};

void main()
{
Graph gh;
gh.InsertVertex('a');
gh.InsertVertex('b');
gh.InsertVertex('c');
gh.InsertVertex('d');
gh.InsertVertex('e');
gh.InsertEdge('a','b');
gh.InsertEdge('a','c');
gh.InsertEdge('b','c');
gh.InsertEdge('b','d');
gh.InsertEdge('c','e');
gh.InsertEdge('d','e');
gh.ShowGraph();
cout<<endl;
gh.DeleteEdge('d','e');
gh.ShowGraph();
cout<<endl;
gh.DeleteVertex('a');
gh.ShowGraph();
cout<<gh.GetEdgeNum('b')<<endl;
cout<<gh.GetVertexI('c')<<endl;
gh.InsertVertex('f');
gh.ShowGraph();
cout<<endl;
gh.InsertEdge('e','f');
gh.ShowGraph();
cout<<endl;
gh.~Graph();
gh.ShowGraph();
cout<<endl;
}