BFS_DFS深度广度优先C++实现。

BFS_DFS深度广度优先C++实现。
#include <iostream>
#include <cstdlib>
#include <set>
#include <vector>
#include <list>
#include <stack>
#include <queue>

using namespace std;

//BFS
void bfs(vector< list<int> >& adj_lists, int start_node) {

    queue<int> not_yet_explored;
    set<int> discovered;

    // 标记起始结点为已被发现, 并将其放入队列中开始探索
    not_yet_explored.push(start_node);
    discovered.insert(start_node);

    while (! not_yet_explored.empty()) {

        // 获得一个新结点并依此作为基点进行探索
        int node_to_explore = not_yet_explored.front();
        not_yet_explored.pop();
        // 检测该结点的所有边
        list<int>::iterator edges = adj_lists[node_to_explore].begin();
        for ( ; edges != adj_lists[node_to_explore].end(); edges++) {

            if (discovered.count(*edges) == 0) {

                // 发现新结点将其加入队列
                discovered.insert(*edges);
                not_yet_explored.push(*edges);

                cout <<"Found "<< *edges <<" from "<<node_to_explore<<endl;

            }
        }
    }
}
//DFS
void dfs_helper(vector< list<int> >& adj_lists, set<int>& discovered, int node) {

    //  检测该结点的所有边
    list<int>::iterator edges = adj_lists[node].begin();
    for ( ; edges != adj_lists[node].end(); edges++) {
        // 检测某条边是否含有未发现的顶点
        if (discovered.count(*edges) == 0) {
            discovered.insert(*edges);
            cout << "Found " << *edges << " from " << node << endl;
            dfs_helper(adj_lists, discovered, *edges);
        }
    }
}

void dfs(vector< list<int> >& adj_lists, int start_node) {

    //标记起始顶点为已被发现
    set<int> discovered;
    discovered.insert(start_node);
    dfs_helper(adj_lists, discovered, start_node);
}


int main(int argc, char* argv[])
{
    int n=0,tmp;
    cout << "please enter n:\t";
    scanf("%d",&n);
    vector< list<int> > g(n, list<int>());
    for(int i=0; i<n; i++){
    cout << "please \"point\"= "<< i << " ,enter\"9999\" finish" <<endl;
        while(cin >> tmp, tmp!=9999){
        g[i].push_back(tmp);
    }
    }



    cout << "BFS" <<endl;
    bfs(g, 0);

    cout << endl << "DFS" <<endl;
    dfs(g, 0);

    return 0;
}

BFS_DFS深度广度优先C++实现。

    原文作者:BFS
    原文地址: https://blog.csdn.net/Lina_ACM/article/details/52749106
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞