图的遍历(邻接表存储)

邻接表的存储方式为

#include <bits/stdc++.h>
 
using namespace std;
 
int main()
{
    map<string,set<string>> m;
    for(int i = 0;i < 10;++i)
    {
        string x,y;
        cin >> x >> y;
        m[x].insert(y);
        m[y].insert(x);
    }
    return 0;
}

遍历的方式主要分为BFSDFS 

主要遍历该图:

BFS

void BFS(map<string,set<string>> m,string e)
{
    deque<string> d;
    set<string> check;
    check.insert(e);
    d.push_back(e);
    while(!d.empty())
    {
        auto t = d.front();
        cout << t << endl;
        for(auto elem : m[t])
        {
            if(check.find(elem) == check.end())
            {
                d.push_back(elem);
                check.insert(elem);
            }
        }
        d.erase(d.begin());
    }
}

DFS

set<string> check;
void DFS(map<string,set<string>> m,string e)
{
    check.insert(e);
    cout << e << endl;
    for(auto elem : m[e])
    {
        if(check.find(elem) == check.end())
        {
            DFS(m,elem);
            check.insert(elem);
        }
    }
}

注意这个check要仍在外面

图的遍历一般只能统计节点的属性,不能用于最短路径

#include <bits/stdc++.h>

using namespace std;

void BFS(map<string,set<string>> m,string e)
{
    deque<string> d;
    set<string> check;
    check.insert(e);
    d.push_back(e);
    while(!d.empty())
    {
        auto t = d.front();
        cout << t << endl;
        for(auto elem : m[t])
        {
            if(check.find(elem) == check.end())
            {
                d.push_back(elem);
                check.insert(elem);
            }
        }
        d.erase(d.begin());
    }
}

set<string> check;
void DFS(map<string,set<string>> m,string e)
{
    check.insert(e);
    cout << e << endl;
    for(auto elem : m[e])
    {
        if(check.find(elem) == check.end())
        {
            DFS(m,elem);
            check.insert(elem);
        }
    }
}

int main()
{
    map<string,set<string>> m;
    for(int i = 0;i < 10;++i)
    {
        string x,y;
        cin >> x >> y;
        m[x].insert(y);
        m[y].insert(x);
    }
    cout << "BFS\n";
    BFS(m,"A");
    cout << "DFS\n";
    DFS(m,"A");
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值