一、什么是链式前向星
简单理解为一种存储图的高效的新方法。
二、写法总结
分模块写法
各数据结构的意义
edges[i].to
:表示第 i 条边的终点。edges[i].next
:表示与第 i 条边同起点的下一条边的存储位置。edges[i].w
:为边权head[i]
:表示以 i 为起点的第一条边存储的位置,实际上你会发现这里的第一条边存储的位置其实在以 i 为起点的所有边的最后输入的那个编号。- 所以在遍历的时候,我们得到的图的边和加边的顺序是相反的。
addEdge(int u, int v, int w)
void addEdge(int u, int v, int w) {
edges[tot] = new Edge();
edges[tot].to = v;
edges[tot].w = w;
edges[tot].next = head[u]; //找到以点 i 为起点的最尾巴的一条边的位置
head[u] = tot++;
}
遍历图
int v = queue.poll();
for (int i = head[v]; i != 0; i = edges[i].next) {
int to = edges[i].to;
...
}
参考链接:https://blog.csdn.net/acdreamers/article/details/16902023