求最短路径时使用邻接矩阵,当边数M远小于点数N的平方时,我们称为稀疏图,M相对较大的图称为稠密图。稀疏图会造成内存空间的浪费(使用了N*N矩阵存储),而算法复杂度也与矩阵大小的平方成正比关系,这时使用邻接表可以降低时间复杂度。
有向图邻接表的实现
#define _CRT_SECURE_NO_WARNINGS
#include
#include
#include
/*
样例输入
5 4
1 2 1
1 3 1
1 4 1
2 5 1
*/
typedef struct EdgeNode//边节点
{
int next_point;
int weight;
EdgeNode* next;
}EdgeNode;
typedef struct point
{
int exist = 0;
EdgeNode* head = NULL;
}point;//初始值为0.存在节点赋值为1
point point_list[100];//点集
int main() {
int num_point, num_edge;
scanf("%d %d", &num_point, &num_edge);//点数 边数
for (int i = 1; i <=num_point; i++)
{
point_list[i].exist = 1;
}
int w, vi, vj;
for (int i = 1; i <= num_edge; i++)//申请内存,建立邻接表
{
scanf("%d %d %d", &vi, &vj,&w);
EdgeNode* e = (EdgeNode*)malloc(sizeof(EdgeNode));
e->weight = w;
e->next_point = vj;
e->next = point_list[vi].head;
point_list[vi].head = e;
}
//读取对应点上相邻的点
int p;
scanf("%d", &p);
if (point_list[p].exist==1)
{
EdgeNode* cur = point_list[p].head;
while (cur!=NULL)
{
printf("%d ", cur->next_point);
cur = cur->next;
}
}
return 0;
}