BFS&DFS

BFS 广度优先遍历算法

Lists are sequence containers that allow constant time insert and erase operations anywhere within the sequence, and iteration in both directions.

Compared to other base standard sequence containers (array, vector and deque), lists perform generally better in inserting, extracting and moving elements in any position within the container for which an iterator has already been obtained, and therefore also in algorithms that make intensive use of these, like sorting algorithms.

list对于插入与删除有较高的效率,且自定义sort函数。

#include <list>
#include <vector>

class Graph
{
    int V;    //顶点数目
    list<int> *adj;    //指向存储顶点的空间
public:
    Graph(int V);  
    void addEdge(int v, int w);
    void BFS(int s); 
};

Graph::Graph(int V)
{
    this->V = V;
    adj = new list<int>[V];
}

void Graph::addEdge(int v, int w)
{
    adj[v].push_back(w); //将顶点w加入顶点v的list中
}

void Graph::BFS(int s)
{
    vector<bool> visited(V,false);
    list<int> queue;

    visited[s] = true;
    queue.push_back(s);

    list<int>::iterator i;

    while(!queue.empty())
    {
        s = queue.front();
        cout << s << " ";
        queue.pop_front();

        for(i = adj[s].begin(); i != adj[s].end(); ++i)
        {
            if(!visited[*i])
            {
                visited[*i] = true;
                queue.push_back(*i);
            }
        }
    }
}

DFS 深度优先遍历算法

#include <list>
#include <vector>

class Graph {
    int n;
    list<int> *adj;
    void DFSUtil(int v, vector<bool> &visited);
public:
    Graph(int n);
    void addEdge(int v, int w);
    void DFS(int v);
};

Graph::Graph(int n)
{
    this->n = n;
    adj = new list<int>[n];
}

void Graph::addEdge(int v, int w)
{
    adj[v].push_back(w);
}

void Graph::DFSUtil(int v, vector<bool> &visited)
{
    visited[v] = true;
    cout << v << ' ';

    list<int>::iterator i;
    for (i = adj[v].begin(); i != adj[v].end(); i++)
    {
        if (!visited[*i])
        {
            DFSUtil(*i, visited);
        }
    }
}

void Graph::DFS(int v)
{
    vector<bool> visited(n,false);

    for (int i = 0; i < n; i++)
    {
        if (visited[i] == false)
        {
            DFSUtil(v, visited);
        }
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值