演算法學習,演算法學習網站
深度優先遍曆
在圖的遍曆中,其中深度優先遍曆和廣度優先遍曆是最常見,也最簡單的兩種遍曆方法。
深度優先遍曆的思想就是一直向下找,找到盡頭之後再去其他分支尋找。
在上一篇部落格中我已經寫了廣度優先遍曆(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中。