算法学习 - 图的深度优先遍历(DFS) (C++)
2015-04-01 15:48
225 查看
深度优先遍历
在图的遍历中,其中深度优先遍历和广度优先遍历是最常见,也最简单的两种遍历方法。深度优先遍历的思想就是一直向下找,找到尽头之后再去其他分支查找。
在上一篇博客中我已经写了广度优先遍历(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 4 using 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; }
测试用例:
2 2 1 4 1 0 1 2 1 2 2 1 3 1
这个是输入,每行的数字是节点出度,紧跟的是其相邻节点。
输出: 1 2 4 3
如此。此测试用例也可以用到我上一篇博客的BFS中。
相关文章推荐
- 算法学习:图的深度优先遍历(DFS)
- 算法学习 - 括号匹配(栈实现)C++
- 算法学习 - Gray Code(格雷码)的解释和c++实现
- #数据结构与算法学习笔记#剑指Offer1.5:二维数组中的查找(C++)
- C++基础算法学习——熄灯问题
- 算法学习记录十一(C++)--->调整数组顺序使奇数前偶数后
- C++ 学习笔记---善良的算法讲解
- C++基础算法学习——逆波兰表达式问题
- 图的遍历算法DFS和BFS(C++)
- C++学习之泛型算法概述--摘自C++primer4
- C++精华(STL)学习笔记之算法
- C++学习整理(泛型算法)
- 算法学习——搜索和C++ STL 实现全排列和去重全排列
- c++学习之插入算法
- C++ 学习笔记(10)泛型算法、lambda表达式、bind函数、迭代器
- 学习算法 - 表指针实现~ C++
- C++学习笔记2.2 : 容器和算法之关联容器
- 算法学习 - 动态规划(DP问题)装配线问题(C++)
- 算法导论-第22章-基本的图算法:强连通分量(深度优先遍历基础上)C++实现
- c++学习9之泛型算法