您的位置:首页 > 编程语言 > C语言/C++

算法学习 - 图的深度优先遍历(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++ 遍历