演算法學習,演算法學習網站

來源:互聯網
上載者:User

演算法學習,演算法學習網站
深度優先遍曆

在圖的遍曆中,其中深度優先遍曆和廣度優先遍曆是最常見,也最簡單的兩種遍曆方法。

深度優先遍曆的思想就是一直向下找,找到盡頭之後再去其他分支尋找。

在上一篇部落格中我已經寫了廣度優先遍曆(BFS)。
想看的傳送門:圖的廣度優先遍曆

代碼實現

這裡實現和BFS的差別在於,在BFS中,我們使用的容器是隊列(queue),是先進先出的, 而在DFS中我們需要使用的是棧(stack)一個先進後出的容器。

其他基本原理相同。

////  main.cpp//  DFS////  Created by Alps on 15/4/1.//  Copyright (c) 2015年 chen. All rights reserved.//#include <iostream>#include <stack>#define Vertex int#define WHITE 0#define GRAY 1#define BLACK 2#define NumVertex 4using namespace std;struct node{    int val;    int weight;   // if your graph is weight graph    struct node* next;    node(int v, int w):val(v), weight(w), next(NULL){}};typedef node* VList;struct TableEntry{    VList header;    Vertex color;};typedef TableEntry Table[NumVertex+1];void InitTableEntry(Vertex start, Table T){    Vertex outDegree;    VList temp = NULL;    for (int i = 1; i <= NumVertex; i++) {        scanf("%d", &outDegree);        T[i].header = NULL;        T[i].color = WHITE;        for (int j = 0; j < outDegree; j++) {            temp = (VList)malloc(sizeof(struct node));            scanf("%d %d", &temp->val, &temp->weight);            temp->next = T[i].header;            T[i].header = temp;        }    }    T[start].color = GRAY;}void DFS(Vertex start, Table T){    stack<Vertex> S;    S.push(start);    Vertex V;    VList temp;    while (!S.empty()) {        V = S.top();        printf("%d ", V);        T[V].color = BLACK;        S.pop();        temp = T[V].header;        while (temp) {            if (T[temp->val].color == WHITE) {                S.push(temp->val);                T[temp->val].color = GRAY;            }            temp = temp->next;        }    }}int main(int argc, const char * argv[]) {    Table T;    InitTableEntry(1, T);    DFS(1, T);    return 0;}

測試案例:

22 14 1012 122 13 1

這個是輸入,每行的數字是節點出度,緊跟的是其相鄰節點。

輸出: 1 2 4 3

如此。此測試案例也可以用到我上一篇部落格的BFS中。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.