1.邻接矩阵
一维数组存储顶点信息,用二维数组存储边信息。空间复杂度为O(n^2),无向图的邻接矩阵一定是对称的,它的第i行或者第j列不为0或者∞的元素个数正好是 顶点 i或者j的度。用邻接矩阵很容易知道两条边之间是否有边相连,而且也很直观简单。但是要确定图中有多少条边的时间复杂度是O(n^2),在存储稀疏图时还会浪费大量的空间,这是邻接矩阵的局限性。
2.邻接表
邻接表是采用链表的方法。将所有与顶点vi相连接的边连成一个单向链表。在邻接表中有两种接点结构:顶点表和边表。顶点表包括顶点域Vertex和边的表头指针,边表包括邻接点域边上信息(weight)和指针域。若无向图有n个顶点和e条边,则邻接表有n个顶点和2*e条边结点。相对于邻接矩阵而言,邻接表节省了大量的空间,而且可以在O(n+e)时间内确定图中有多少条边,但是操作起来略复杂。
下面是邻接表代码:
#include<iostream>
using namespace std;
#define MAX_SIZE 1000
struct Enode{
int weight; //权重
int Advj; //顶点下标
Enode*next;
};
struct Vnode{
int date; //顶点卫星数据
Enode*firstedge; //指向第一条边的指针
};
struct AdjList{ //邻接表
int v, e;
Vnode Vetex[MAX_SIZE];
};
void CreatGraph(AdjList*Graph);
int main(){
int i;
AdjList *Graph=new AdjList;
CreatGraph(Graph);
Enode*edge;
for (i = 0; i < Graph->v; i++){
cout <<"顶点:"<<i<<" 数据域:"<< Graph->Vetex[i].date<<" 邻接点和权重:";
edge = Graph->Vetex[i].firstedge;
while (edge){
cout << "(" << edge->Advj << ',' << edge->weight << ") ";
edge = edge->next;
}
cout << endl;
}
}
void CreatGraph(AdjList*Graph){
int i, j,w,k;
Enode*edge;
cin >> Graph->v >> Graph->e;
for (i = 0; i < Graph->v; i++){
cin >> Graph->Vetex[i].date;
Graph->Vetex[i].firstedge = nullptr; //输入边信息并初始化
}
for (k =0; k< Graph->e;k++){
cin >> i >> j >> w;
edge = new Enode;
edge->Advj = j;
edge->weight = w;
edge->next = Graph->Vetex[i].firstedge;
Graph->Vetex[i].firstedge = edge;
//------------------------------------
edge = new Enode;
edge->Advj = i;
edge->weight = w;
edge->next = Graph->Vetex[j].firstedge;
Graph->Vetex[j].firstedge = edge;
}
}