算法学习 - 图的深度优先遍历(DFS) (C++)

深度优先遍历

在图的遍历中,其中深度优先遍历和广度优先遍历是最常见,也最简单的两种遍历方法。

深度优先遍历的思想就是一直向下找,找到尽头之后再去其他分支查找。

在上一篇博客中我已经写了广度优先遍历(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中。

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值