图的深度优先遍历和广度优先遍历
#include <iostream>
#include <cstdlib>
#include <set>
#include <vector>
#include <list>
#include <stack>
#include <queue>
using namespace std;
//BFS 广度优先遍历
void bfs(vector< list<int> >& adj_lists,int start_node)
{
queue<int> not_yet_explored;
set<int> discovered;
//标记起始结点为已被发现,并将其放入队列中开始探索
not_yet_explored.push(start_node);
discovered.insert(start_node);
while(!not_yet_explored.empty())
{
//获得一个新结点并依此作为基点进行探索
int node_to_explore = not_yet_explored.front();
not_yet_explored.pop();
//检测该结点的所有边
list<int>::iterator edges = adj_lists[node_to_explore].begin();
for (;edges != adj_lists[node_to_explore].end();edges++)
{
if (discovered.count(*edges)==0)
{
//发现新结点将其加入队列
discovered.insert(*edges);
not_yet_explored.push(*edges);
cout<<"Found "<<*edges<<" from "<<node_to_explore<<endl;
}
}
}
}
//DFS 深度优先遍历
void dfs_helper(vector< list<int> >& adj_lists,set<int>& discovered,int node)
{
//检测该结点的所有边
list<int>::iterator edges = adj_lists[node].begin();
for (;edges != adj_lists[node].end();edges++)
{
//检测某条边是否含有未发现的顶点
if (discovered.count(*edges) == 0)
{
discovered.insert(*edges);
cout<<"Found "<<*edges<<" from "<<node<<endl;
dfs_helper(adj_lists,discovered,*edges);
}
}
}
void dfs(vector< list<int> >& adj_lists,int start_node)
{
//标记起始结点为已被发现
set<int> discovered;
discovered.insert(start_node);
dfs_helper(adj_lists,discovered,start_node);
}
int main()
{
//初始化图信息
vector< list<int> > g(7,list<int>());
g[0].push_back(2);
g[0].push_back(1);
g[1].push_back(0);
g[1].push_back(2);
g[2].push_back(4);
g[2].push_back(3);
g[2].push_back(0);
g[2].push_back(1);
g[3].push_back(2);
g[3].push_back(4);
g[4].push_back(6);
g[4].push_back(5);
g[4].push_back(3);
g[4].push_back(2);
g[5].push_back(4);
g[5].push_back(3);
g[6].push_back(4);
cout<<"BFS"<<endl;
bfs(g,0);
cout<<endl<<"DFS"<<endl;
dfs(g,0);
return 1;
}