邻接表的存储方式为
#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;
}
遍历的方式主要分为BFS和DFS
主要遍历该图:
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;
}