【图论】写法总结之「链式前向星」

一、什么是链式前向星

简单理解为一种存储图的高效的新方法。
在这里插入图片描述

二、写法总结

分模块写法

各数据结构的意义

  • 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

发布了691 篇原创文章 · 获赞 151 · 访问量 4万+

猜你喜欢

转载自blog.csdn.net/qq_43539599/article/details/105493190