动态添加到图形数据结构中

Dynamically adding to a graph data structure

本文关键字:数据结构 图形 添加 动态      更新时间:2023-10-16

让我首先声明,我只想要方向,而不一定是实际的代码,除非一个小片段是理解这一点的唯一方法。

我需要使用C++中的邻接列表或矩阵创建一个DIRECTED图数据结构,并从标准输入中添加顶点/边,这意味着动态。

我想如果我能够先实例化一组顶点,然后创建边并将其添加到图中,我就能很好地创建一个图,但我不明白如何添加一条包含尚未实例化的顶点的边。

例如,标准输入的第一行显示:

迈阿密->纽约/1100->华盛顿/1000->阿尔伯克基/1700

如果纽约顶点还没有添加到图中,我应该如何添加从迈阿密到纽约的边?

谢谢大家的指导!

如何添加一条边包含一个尚未实例化的顶点。

简单:实例化它..

我认为这没有任何问题。假设V是迄今为止看到的顶点集。CCD_ 2最初是空的。当您读取输入x->y时,您会得到它的端点(xy)。如果其中任何一个未实例化(即,不在V中),则实例化它并将其添加到顶点集。

另一种方法是:假设我们通过图的边集E来定义图。根据定义,任何边都是一对顶点,这对顶点又定义了图的顶点集。

每次出现新的唯一节点时,如何调整邻接列表的大小?您可以维护一组唯一的节点值,并在每次添加节点时使用其大小来调整邻接列表的大小。下面是一些执行相同操作的代码。

class Graph
{
    public:
    // Add links in the graph
    void addLink(int id1, int id2){
        // Add to hashset
        uniqueNodes.insert(id1);
        uniqueNodes.insert(id2);
        // Resize on the adjacency list based on how many nodes exists in the uniqueNodes set
        adjList.resize(uniqueNodes.size());
        // Make the connections assuming undirected graph
        adjList[id1].push_back(id2);
        adjList[id2].push_back(id1);
    }
    // Print the graph
    void printGraph(){
        for(int i = 0; i < adjList.size(); i++){
            cout << i << ":";
            for(auto it = adjList[i].begin(); it != adjList[i].end(); it++)
                cout << *it << "->";
            cout << "NULLn";
        }
    }
    private:
    // Adjacency list for the graph
    vector<list<int>> adjList;
    // Hashset to help define the size of the adjacency list as nodes come in
    set<int> uniqueNodes;
};