数据挖掘之社交网络 DFS和BFS算法

来源:互联网 发布:网络调研的方法有哪些 编辑:程序博客网 时间:2024/05/16 08:47

源码:

#include <cstdio>#include <list>#include <vector>#include <queue>using namespace std;int n;vector< list<int> > graph;      // 创建叫graph的类型为list<int>链表的容器bool visited[100] = {0};        //visited存储某个节点是否被访问过void dfs(int v){    list<int>::iterator it;     //iterator是C++标准库,对链表进行遍历    visited[v] = true;    printf("%5d", v);    for (it = graph[v].begin(); it != graph[v].end(); ++it)        if (!visited[*it])            dfs(*it);}void bfs(int v){    list<int>::iterator it;    printf("%5d", v);    visited[v] = true;    queue<int> t;    t.push(v);    while (!t.empty())    {        v = t.front();        t.pop();        for (it = graph[v].begin(); it != graph[v].end(); ++it)            if (!visited[*it])            {                printf("%5d", *it);                t.push(*it);                visited[*it] = true;            }    }    cout << endl;}int main(){    //freopen("in.txt", "r", stdin);    cout << "input the vertex num:"<< endl;    cin >> n;                                     //cin the num of nodes    vector< list<int> >::iterator it;    for (int i = 0; i < n; ++i)    {        list<int> il;        int t;        while (cin >> t && t != n)                   //cin the num of nodes as the end of every list            il.push_back(t);                         //push_back( )在vector类中作用为在vector尾部加入一个数据        graph.push_back(il);    }    cout << "result for bfs:" << endl;    bfs(0);                                                 //首先访问起始定点V(所以输入的链表向量的起点应该为0)    memset(visited, 0, sizeof(visited));                   //重新初始化标志数组, void *memset(void *s, int ch, size_t n);将s中前n个字节用 ch 替换并返回 s 。                                                           //memset:作用是在一段内存块中填充某个给定的值,它是对较大的结构体或数组进行清零操作的一种最快方法    cout << "result for dfs:" << endl;    dfs(0);  //首先访问起始定点V(所以输入的链表向量的起点应该为0)    system("pause");    return 0;}
实例:

本文以9个节点的网络图为例:



故输入的链表向量(这里每个链表以nodes个数9表示结束)和结果如下:



本文源码部分转自:http://www.cnblogs.com/PegasusWang/archive/2013/04/06/3002511.html

PS:该文作者以实例将代码演示了一遍,十分有利于初学者理解,感谢作者

本文主要方便自己以及初学者学习(转载请注明出处)



参考文章链接:

 1.图的dfs与bfs(深搜广搜)c++实现

 2.广度优先搜索的实现

 3.C++ vector之iterator

 4.C++ STL--stack/queue 的使用方法

 5.改进:









1 0