BFS 和 DFS ( 1 )

参考:

https://www.bilibili.com/video/av25763384/?spm_id_from=333.788.videocard.0

https://blog.csdn.net/qq_34823530/article/details/99202899

 

 

一,代码

#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<stdlib.h>
#include<vector>
#include<queue>
#include<stack>
#include<map>
using namespace std;
map<char, vector<char>>v;  // 邻接表
void BFS(char start)
{
    queue<char>q;
    vector<int>vis;
    q.push(start);    // 添加起点
    vis.push_back(start);

    while (q.size())
    {
        char vertex = q.front(); // 队首出队列
        q.pop();

        vector<char>vs = v[vertex]; // 取 vertex 的所有邻接点
        for (int i = 0; i < vs.size(); i++)
        {
            char next = vs[i]; // 邻接点
            auto ret = find(vis.begin(), vis.end(), next); 
            if (ret == vis.end())  // 如果 next 没有遍历过的话
            {
                q.push(next);
                vis.push_back(next);
            }
        }
        printf("%c ", vertex);
    }puts("");
}
void DFS(char start)
{
    stack<int>s;
    vector<char>vis;
    s.push(start);    // 添加起点
    vis.push_back(start);

    while (s.size())
    {
        char vertex = s.top(); // 栈顶出队列
        s.pop();

        vector<char>vs = v[vertex]; // 取 vertex 的所有邻接点
        for (int i = 0; i < vs.size(); i++)
        {
            char next = vs[i]; // 邻接点
            auto ret = find(vis.begin(), vis.end(), next);
            if (ret == vis.end())  // 如果 next 没有遍历过的话
            {
                s.push(next);
                vis.push_back(next);
            }
        }
        printf("%c ", vertex);
    }puts("");
}
int main(void)
{
    int n, m;
    while (scanf("%d%d", &n, &m) != EOF)
    {
        char s, s1, s2;
        scanf("%c%c%c", &s1, &s, &s2);  // 起点
        for (int i = 0; i < m; i++)
        {
            char t1, t2, t3, t4;
            scanf("%c%c%c%c", &t1, &t3, &t2, &t4);
            vector<char>vv = v[t1]; // 取出 t1 原来的所有邻接点
            vv.push_back(t2);        // 增加一个邻接点
            v[t1] = vv;                // 覆盖掉原来的邻接点
        }
        printf("BFS:");
        BFS(s);
        printf("DFS:");
        DFS(s);
    }


    system("pause");
    return 0;
}
/*
测试数据:
6 16
A
A B
A C
B A
B C
B D
C A
C B
C D
C E
D B
D C
D E
D F
E C
E D
F D
测试结果:
BFS:A B C D E F
DFS:A C E D F B
*/
View Code

 

二,过程解析

测试数据:

1,BFS

  BFS 是利用队列实现的,由于队列是先进先出的,所以每次同时放进队列的同一个点的邻接点 A,B 都是按顺序来的。它是先 A 后 B。

 

2,DFS

  DFS 是利用栈实现的,由于栈先进后出的。所以每次同时放进栈的同一个点的邻接点 A,B,并不按顺序遍历。它是先 A,在遍历 A 的所有子孙结点,再 B,再遍历 B 的所有子孙结点。

 

 

=========== ========== ========= ====== ===== ==== === == =

 

posted @ 2020-03-06 23:26  叫我妖道  阅读(270)  评论(0编辑  收藏  举报
~~加载中~~