簡體   English   中英

使用鄰接表在 C++ 中實現 DFS(使用<vector>和鏈表)

[英]DFS implementation in c++ using adjacency list (using <vector> and linked list)

我已經使用和鏈接列表制作了一個鄰接列表。 在節點的結構中,我有數據,next 和visited。 當我嘗試在 DFS 函數中將visited 設置為true 時,算法無法正常工作。 它僅在我創建一個存儲布爾值的新數組並將該數組用於 dfs 算法時才有效。 我需要幫助讓訪問頂點結構的成員工作。 我不確定為什么它不起作用。

圖.h

#ifndef GRAPH_H
#define GRAPH_H
#include <vector>

class Graph{
private:
    struct vertex{
        int data;
        bool visited;
        struct vertex* next;
    };

    struct adjList
    {
        struct vertex *head;
    };

    int V;
    bool visited[100];
    std::vector<adjList> G;
public:
    Graph(int vertices);
    vertex* addVertex(int data);
    void addEdge(int index, int data);
    void dfs(int vertex);
    void printGraph();
};

#endif

圖.cpp

#include "Graph.h"
#include <iostream>
#include <cstdlib>
using namespace std;

Graph:: Graph(int vertices){
    this->V=vertices;
    for(int i=0; i<V; i++){
        //allocating space in G for V amount and using constructor of struct
        G.push_back(adjList());
        visited[i]=false;
    }
}
//create a node
Graph:: vertex* Graph::addVertex(int data){
    struct vertex* newNode= new vertex;
    newNode->data= data;
    newNode->next= NULL;
    newNode->visited=false;
    return newNode;
}
//add an Edge to the list
void Graph:: addEdge(int index, int data){
    struct vertex* cursor= G[index].head;
    while(cursor){
      if(cursor->data==data)
        return;
      cursor= cursor->next;
    }
    struct vertex* newVertex= addVertex(data);
    newVertex->next = G[index].head;
    G[index].head= newVertex;
    // this is undirected graph, so we are adding an edge from data to index;
    newVertex = addVertex(index);
    newVertex->next= G[data].head;
    G[data].head= newVertex;
}
// dfs algorithm
void Graph::dfs(int vertex){
    cout<<vertex<<", ";
    G[vertex].head->visited = true;
    visited[vertex]=true;
    struct vertex* cursor = G[vertex].head;
    while(cursor!=NULL){
      vertex=cursor->data;
      if(visited[vertex]==false)
          dfs(vertex);
      cursor= cursor->next;
    }
}

void Graph::printGraph(){
    for(int i=0; i<V; i++){
        struct vertex* cursor= G[i].head;
        cout<<"vertex: "<<i<<endl;
        while(cursor!=NULL){
            cout<<"->"<<cursor->data;
            cursor=cursor->next;
        }
        cout<<endl;
    }
}

int main(){
    Graph Graph(5);
    Graph.addEdge(0,1);
    Graph.addEdge(0,4);
    Graph.addEdge(1,2);
    Graph.addEdge(1,3);
    Graph.addEdge(1,4);
    Graph.addEdge(2,3);
    Graph.addEdge(3,4);

    Graph.printGraph();
    Graph.dfs(0);
    return 0;
}

首先清理你的數據結構,你過早地將它們轉向支持你的算法,這會帶來一些混亂。 首先確保您有一些可靠的“模型”,沒有考慮任何算法,然后檢查算法需要什么,並將其添加為本地臨時內部算法,或添加到模型中的一些緩存/擴展數據。 但保持核心模型在它之下。

我的意思是,讓我向您展示 DFS 的超級低效但簡單的實現,希望可以被視為“現代 C++”(但我也不是專家):

現場演示: http : //cpp.sh/9fyw

#include <iostream>
#include <vector>
#include <string>

/**
 * Super naive and inefficient (but simple) implementation of Depth-first-search of graph
 * Just to show basic usage of std::vector, and how it helps to avoid new/delete
 **/

struct Vertex {
    // nothing at the moment
};

struct Edge {   // One-way edge, to make things intentionally harder
    size_t fromIndex, toIndex;

    Edge(const size_t _fromIndex, const size_t _toIndex)
        : fromIndex(_fromIndex), toIndex(_toIndex) {}
};

class Graph {
    std::vector<Vertex> vertices;
    std::vector<Edge> edges;

public:
    Graph(const size_t expectedVerticesCount = 20, const size_t expectedEdgesCount = 50) {
        if (expectedVerticesCount) vertices.reserve(expectedVerticesCount);
        if (expectedEdgesCount) edges.reserve(expectedEdgesCount);
    }

    void clear() {
        vertices.clear();
        edges.clear();
    }

    void initVertices(const size_t newVertexCount) {
        // A bit pointless function to set vertices, as vertices have no data
        // Storing the count itself inside Graph would suffice,
        // but let's demonstrate vector usage a bit more with N empty vertices
        clear();    // removes old vertices + edges
        vertices.resize(newVertexCount);
    }

    void addEdgeBiDirectional(const size_t v1Index, const size_t v2Index) {
        if (vertices.size() <= v1Index || vertices.size() <= v1Index) {
            std::cout << "Ups, unexpected vertex in edge: "
                << v1Index << " <-> " << v2Index << "\n";
            return;
        }
        if (v1Index == v2Index) {
            std::cout << "Ups, loop at vertex: " << v1Index << " - ignored\n";
            return;
        }
        // Add two one-way edges, to make this edge work in both directions
        edges.push_back(Edge(v1Index, v2Index));
        edges.push_back(Edge(v2Index, v1Index));
    }

    void printGraph() {
        for (size_t i = 0; i < vertices.size(); ++i) {
            std::cout << "Vertex " << i << " has edges to:";
            for (const auto & edge : edges) {
                if (edge.fromIndex == i) std::cout << " " << edge.toIndex;
            }
            std::cout << "\n";
        }
    }

private:
    void dfs(std::vector<size_t> & result, std::vector<bool> & visited, size_t v) {
        // It's important to pass vectors as references here (that "&")
        // so you don't fill stack space too quickly, and the modifications
        // done to them inside are propagated up into final result.
        // Without "&" a local copy of vector would be created.
        if (visited[v]) return;
        result.push_back(v);
        visited[v] = true;
        for (const auto edge : edges) {
            if (edge.fromIndex != v) continue;
            dfs(result, visited, edge.toIndex);
        }
    }

public:
    // Returns vector with vertex indices found
    std::vector<size_t> dfs(const size_t vertexIndex) {
        if (vertices.size() <= vertexIndex) {
            std::cout << "DSF: Ups, invalid starting vertex: "
                << vertexIndex << "\n";
            return std::vector<size_t>();
        }

        std::vector<bool> visited(vertices.size());
        std::vector<size_t> result;
        result.reserve(vertices.size());
        dfs(result, visited, vertexIndex);
        return result;
    }
};

int main()
{
    Graph g;
    // fill up graph data
    g.initVertices(5);
    g.addEdgeBiDirectional(0,1);
    g.addEdgeBiDirectional(0,4);
    g.addEdgeBiDirectional(1,2);
    g.addEdgeBiDirectional(1,3);
    g.addEdgeBiDirectional(1,4);
    g.addEdgeBiDirectional(2,3);
    g.addEdgeBiDirectional(3,4);
    // Show the validation works
    g.addEdgeBiDirectional(1,1);
    g.addEdgeBiDirectional(5,4);

    g.printGraph();

    auto dfsResult = g.dfs(2);
    std::cout << "DFS for 2 result:";
    for (const auto v : dfsResult) std::cout << " " << v;
    std::cout << "\n";
}

(現在我意識到,我的“addEdge”並不能防止重復邊緣添加,就像你的一樣,認為它是錯誤或功能)


如果您檢查它,您會發現性能很差,因為它每次都在搜索所有邊。 如何幫助它? 已經為每個頂點准備了鄰居數據。

struct Vertex {
    std::vector<size_t> adjacency;
};

然后在Graph您可以為每個添加的邊設置相鄰頂點:

void addAdjacency(const size_t v1Index, const size_t v2Index) {
    auto & adjacency = vertices[v1Index].adjacency;
    if (adjacency.end() != std::find(adjacency.begin(), adjacency.end(), v2Index)) return;
    adjacency.push_back(v2Index);
}

void addEdgeBiDirectional(const size_t v1Index, const size_t v2Index) {
    ...
    addAdjacency(v1Index, v2Index);
    addAdjacency(v2Index, v1Index);
}

現場演示: http : //cpp.sh/4saoq

現在效率更高了(就深度優先的效率而言,廣度優先搜索會更容易編寫,無需使用大量堆棧空間進行遞歸)。

但是,如果 DFS 和 printGraph 是您唯一的目標,那么可以通過完全刪除edges並僅保留vertices和其中的adjacency來重構。 您可以自己嘗試一下,您會發現它只需要進行很少的更改。

但是visited字段仍然由dfs臨時擁有,IMO 是最適合如何使用它的。


這已經很長了,花了很長時間,我沒有心情向你展示一些帶有指針、新建和刪除的東西。 向您展示如何避免它們可能仍然有更多好處,至少在您可以自己編寫類似或更好的代碼之前。

學習裸指針/新建/刪除內容也很重要,但是......查看一些教程?

至少有一個提示“何時delete ”:在現代 C++ 中,您可以在范圍內思考。 就像一切都屬於某個地方(在某個范圍內),然后在退出范圍時被釋放。 通過這種方式思考,您只需在您的類中實現構造函數+析構函數,就完成了清理工作。

Graph g; 在我的示例中是main局部變量,因此在它的范圍內。 main退出時,調用g的析構函數(我沒有寫,因為默認的析構函數是由編譯器創建來調用verticesedges析構函數,而Vertex析構函數被vector析構函數調用,它隱式調用adjacency析構函數。所以一切都被釋放了,沒有內存泄漏。

如果我在Graph使用一些new生命周期(在構造函數中或在某個函數中),要么我將指針放在某個 Graph 成員變量中,並編寫顯式析構函數檢查非 nullptr 值,然后刪除它,或在某些函數中盡快刪除它(並將存儲設置為 nullptr 以避免對同一指針進行雙重刪除)。

因此,如果您確保您的類設計有意義,並且所有內容都屬於某個合理的范圍,那么您可以使用由構造函數/析構函數配對的new/delete ,並且您知道清理發生在退出范圍時,它確實擁有(是負責)那件作品。

還有其他技術,如何將指針(或實際上的任何資源)從原始所有者傳遞到其他類......通常我會盡力避免這種情況,但如果你真的堅持這樣的應用程序結構,你可以使用東西圍繞std::unique_ptr 但是這種設計很難保持干凈,也很難追蹤特定內存或資源的責任/所有權。 例如,觀看此視頻以了解如何以某種優雅的方式處理它的一些想法。


還有一些關於new和指針以及鏈表的最后說明。 您可能從 Java 到鏈表和哈希映射之類的東西,這在 VM 下是有意義的,因為您幾乎無法控制內存管理,並且實例通常與對象元數據大量“混搭”。

在 C++ 中它是不同的,通常有接近零的開銷,所以std::vector<uint32_t> millionIntegers(1e6); 是一個長度為 400 萬字節的連續內存塊,除此之外還有一些額外的矢量元數據字節。

這意味着,我的第一個 O(n*n) 示例幾乎每次都通過所有邊,可以用於具有 100+k 條邊的圖,性能非常接近帶有指針的 O(n),因為每個new可能結束在內存的不同部分,打破了處理數據的局部性。 當您嘗試訪問緩存內存頁面之外的內存時,這會帶來巨大的性能損失。 雖然以連續方式處理 100k 個整數是 CPU 可以半睡半醒的事情,最大限度地提高緩存吞吐量(不幸的是,深度優先也把它搞砸了)。

這就是為什么通常在編寫第一個版本時您不應該對容器類型感到困擾的原因。 如果vector適合,則使用它。 然后,在您完成工作、測試代碼后,您可以對其進行分析,並嘗試一些更智能的內存結構,最終甚至用某種鏈表替換vector 但是你不能只依賴算法理論或“邏輯”。

當涉及 x86 性能時,通過分析真實生產代碼對真實生產數據的硬數據至關重要,現代硬件可以在許多方面讓人類邏輯大吃一驚,並以意想不到的方式挑戰理論。 為了獲得最佳性能,您既需要相當復雜(簡單)的算法,又需要具有可預測的常規訪問模式的整齊排列的數據。 只有兩者之一可能還不夠。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM