实施加权图

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;