实施加权图
Implement weighted graph
本文关键字:加权图 更新时间:2023-10-16
假设我有以下邻接矩阵:
A B C D
A 0 9 0 5
B 9 0 0 0
C 0 0 0 2
D 5 0 2 0
如何切实执行?我意识到我可以使用2D阵列来表示顶点之间的加权边,但我不知道如何表示顶点。
int edges[4][4];
string vertices[4];
这样做吗?顶点数组中的索引对应于边数组中的行索引。
您可以使用二维std::map
使用这种方法可以让矩阵在任何时候都可以增长和收缩。
#include <map>
#include <string>
#include <iostream>
int main()
{
std::map<std::string, std::map<std::string, int>> vertices;
vertices["A"]["A"] = 0; vertices["A"]["B"] = 9; vertices["A"]["C"] = 0; vertices["A"]["D"] = 5;
vertices["B"]["A"] = 9; vertices["B"]["B"] = 0; vertices["B"]["C"] = 0; vertices["B"]["D"] = 0;
vertices["C"]["A"] = 0; vertices["C"]["B"] = 0; vertices["C"]["C"] = 0; vertices["C"]["D"] = 2;
vertices["D"]["A"] = 5; vertices["D"]["B"] = 0; vertices["D"]["C"] = 2; vertices["D"]["D"] = 0;
std::cout << vertices["A"]["A"] << std::endl;
std::cout << vertices["A"]["B"] << std::endl;
}
将邻接矩阵的索引作为顶点是常见的做法。
如果图中有固定数量的顶点。您可以将顶点声明为枚举,并直接使用枚举的顶点名称对数组进行索引。我认为这会使映射更加清晰。
enum VERTEX
{
A = 0,
B,
C,
D,
LAST = D
};
int edge[LAST+1][LAST+1];
edge[A][A] = 0;
edge[A][B] = edge[B][A] = 9;
edge[A][C] = edge[C][A] = 0;
// etc.
这使您可以在不需要任何查找惩罚的情况下使用数组,同时使事情易于理解,从而使事情变得简单快捷。
对于大多数意图和目的,将图表示为相邻列表通常更有效:
std::vector< std::list<int> > graph;
所以图[i]是i的所有相邻顶点。优点是在处理图时,我们通常想要遍历i的邻居。此外,对于大型稀疏图,空间复杂度要低得多。当然,这也可以扩展到包括权重,比如:
std::vector< std::list<std::pair< int, int> > > graph;
或者对于更复杂的类型,定义一个类型Vertex。。。
编辑:如果您需要将索引作为字符串,可以通过选择std::map而不是std::vector:来轻松完成
std::map< std::string, std::list<std::pair< std::string /*vertex*/, int/*weight*/> > > graph;
但从你最初的帖子中可以看出,你只想将索引映射到顶点名称,在这种情况下,我会使用第一个解决方案,但也会将顶点名称映射到索引:
std::vector< std::pair< std::string/*name*/, std::list<std::pair< int /*index*/, int/*weight*/> > > > graph;
相关文章:
- C / C++ 移位/偏移/向左或向右移动位图?
- 构建可组合有向图(扫描仪生成器的汤普森构造算法)
- 在无向图中打印循环
- 有没有办法在一行中填充矢量图
- 创建有向加权图
- 使用迭代深度优先搜索算法的未加权图的最短路径
- 计算无向未加权图的每个连接部分中的节点数
- 加权图的开始和结束的最短路径
- 加权图的邻接列表表示
- 从CSV创建来自校友矩阵的无向加权图
- 如何以C 的网格形状制作未方向和未加权的图
- 有效的算法可以在无方向的加权图中找到所有周期的权重
- 如何在图中找到3个边缘的负加权周期
- 所有对的最短路径长度为无向加权稀疏图
- 加权无向Boost图上的Floyd-Warshall(所有对最短路径)
- 加权Voronoi的CGAL 2D APOLLONIUS图-如何生成和获取面和顶点
- 圆形、无向、未加权图中的最短路径
- 加权图最短路径设计
- 实施加权图
- C++ 中的无向加权图数据结构