第7章 圖

leetcode刷了一大半,數組,鏈表,樹,隊列和棧的題目已經做了好多,感覺比較紮實了。突然發現後面好多關於圖算法的問題,沒辦法,又繼續開始學習“圖”這種數據結構。折騰了一天,把圖的創建,深度優先級遍歷(DFS)和廣度優先級遍歷(BFS)都用c++寫出來了,算法參照了《算法導論》和《數據結構和算法》。
遍歷是各種圖操作的基本思路,所以一定要熟練掌握。

注:

1. 圖的表示採用了鄰接鏈表,因爲這種結構在存儲方面比較節約空間,在遍歷時的時間複雜度也比用鄰接矩陣時更好,兩種遍歷都爲O(V+E)

2.下面以有向圖來展示遍歷的過程,無向圖類似,只是在添加邊調用addEdge()函數時再加一條相反的邊即可。

/*
A C++ Program to demonstrate adjacency list representation of graphs
Create a adjacency list representation of graphs
BFS based on adjacency list representation of graphs
BFS based on adjacency list representation of graphs
*/
#include <iostream>
#include <queue>
#include <vector>
using namespace std;

// A structure to represent an adjacency list node
struct AdjListNode
{
    int dest;
    AdjListNode* next;
    AdjListNode(int d): dest(d), next(NULL) {}
};

// A structure to represent an adjacency list
struct AdjList
{
    AdjListNode *head;  // pointer to head node of list
    AdjList(): head(NULL) {}
};

// A structure to represent a graph. A graph is an array of adjacency lists.
// Size of array will be V (number of vertices in graph)
struct Graph
{
    int V;
    AdjList* array;
    Graph(int vertex): V(vertex)
    {
        array = new AdjList[V];
        for(int i = 0; i < vertex; i++)
            array[i].head = new AdjListNode(i);
    }
    ~Graph()
    {
        AdjListNode* it;
        AdjListNode* prev;
        for(int i = 0; i < V; i++)
        {
            it = array[i].head;
            while(it)
            {
                prev = it;
                it = it->next;
                delete prev;
            }
        }
        delete[] array;
    }
};

// A utility function to create a new adjacency list node
AdjListNode* newAdjListNode(int dest)
{
    AdjListNode* node = new AdjListNode(dest);
    return node;
}

// A utility function that creates a graph of V vertices
Graph* createGraph(int V)
{
    Graph* graph = new Graph(V);
    return graph;
}

// Adds an edge to an directed graph
void addEdge(struct Graph* graph, int src, int dest)
{
    //src to dest
    AdjListNode* node = newAdjListNode(dest);
    node->next = graph->array[src].head->next;
    graph->array[src].head->next = node;
    /*
    //dest to src (if it's an undirected graph)
    node = newAdjListNode(src);
    node->next = graph->array[dest].head;
    graph->array[dest].head = node;
    */
}

// A utility function to print the adjacenncy list representation of graph
void printGraph(struct Graph* graph)
{
    for (int v = 0; v < graph->V; ++v)
    {
        AdjListNode* pCrawl = graph->array[v].head;
        cout << endl << " Adjacency list of vertex " << v << endl << " ";
        while (pCrawl)
        {
            cout << pCrawl->dest << "-> ";
            pCrawl = pCrawl->next;
        }
        cout << "#" << endl;
    }
}

void BreadthFirstSearch(Graph* graph)
{
    cout << "BreadthFirstSearch print: " << endl;
    queue<AdjListNode*> q;
    vector<bool> visited(graph->V, false);
    AdjListNode* cur = NULL;
    for(int i = 0; i < graph->V; i++)
    {
        if(!visited[i])
        {
            visited[i] = true;
            cout << i << " -> ";
            cur = graph->array[i].head;
            q.push(cur);
            while(!q.empty())
            {
                cur = q.front();
                if(cur->dest < graph->V)
                    cur = graph->array[cur->dest].head;
                q.pop();
                while(cur)
                {
                    if(!visited[cur->dest])
                    {
                        visited[cur->dest] = true;
                        cout << cur->dest << " -> ";
                        q.push(cur);
                    }
                    cur = cur->next;
                }
            }
        }
    }
    cout << "#" << endl;
}

void DFS_helper(Graph* graph, int v, vector<bool>& visited)
{
    cout << v << " -> ";
    if(v >= graph->V || v < 0)
        return;
    visited[v] = true;
    AdjListNode* cur = graph->array[v].head->next;
    while(cur)
    {
        DFS_helper(graph, cur->dest, visited);
        cur = cur->next;
    }
}

void DepthFirstSearch(Graph* graph)
{
    cout << "DepthFirstSearch print: " << endl;
    vector<bool> visited(graph->V, false);
    for(int i = 0; i < graph->V; i++)
    {
        if(!visited[i])
            DFS_helper(graph, i, visited);
    }
    cout << "#" << endl;
}

// Driver program to test above functions
int main()
{
    // create the graph given in above fugure
    int V = 7;
    struct Graph* graph = createGraph(V);
    addEdge(graph, 0, 2);
    addEdge(graph, 0, 1);
    addEdge(graph, 1, 4);
    addEdge(graph, 1, 3);
    addEdge(graph, 2, 6);
    addEdge(graph, 2, 5);
    addEdge(graph, 3, 7);

    // print the adjacency list representation of the above graph
    printGraph(graph);
    //BFS and DFS
    BreadthFirstSearch(graph);
    DepthFirstSearch(graph);
    return 0;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章