#include<iostream>
#include<vector>
#include<algorithm>
#include<map>
#include<stack>
#include<iterator>
using namespace std;
void BFS(map<char,vector<char>> m, char start) {
vector <char> q; char vertex; vector <char> nodes;
vector <char> seen; seen.push_back(start);
q.push_back(start);
while (q.size()>0)
{
vertex = q[0];
q.erase(q.begin());
nodes = m[vertex];
for (char w : nodes) {
auto ret = find(seen.begin(), seen.end(), w);
if (ret == seen.end())
{
q.push_back(w);
seen.push_back(w);
}
}
cout << vertex<<endl;
}
}
void DFS(map<char, vector<char>> m, char start) {
stack <char> q; char vertex; vector <char> nodes;
vector <char> seen; seen.push_back(start);
q.push(start);
while (q.size() > 0)
{
vertex = q.top();
q.pop();
nodes = m[vertex];
for (char w : nodes) {
auto ret = find(seen.begin(), seen.end(), w);
if (ret == seen.end())
{
q.push(w);
seen.push_back(w);
}
}
cout << vertex << endl;
}
}
int main() {
vector<char> a{'B', 'C'};
vector<char> b{'A', 'C', 'D'};
vector<char> c{ 'A', 'B', 'D','E' };
vector<char> d{ 'B', 'C', 'E','F' };
vector<char> e{ 'C', 'D' };
vector<char> f{ 'D' };
map <char, vector<char>> m{ {'A',a},{'B',b},{'C',c},{'D',d},{'E',e},{'F',f} };
DFS(m, 'A');
//BFS(m,'A');
}
视频链接 https://www.bilibili.com/video/av25763384
照着up写的,python确实简洁很多