源码:
#include <cstdio>
#include <list>
#include <vector>
#include <queue>
using namespace std;
int n;
vector< list<int> > graph; // 创建叫graph的类型为list<int>链表的容器
bool visited[100] = {0}; //visited存储某个节点是否被访问过
void dfs(int v)
{
list<int>::iterator it; //iterator是C++标准库,对链表进行遍历
visited[v] = true;
printf("%5d", v);
for (it = graph[v].begin(); it != graph[v].end(); ++it)
if (!visited[*it])
dfs(*it);
}
void bfs(int v)
{
list<int>::iterator it;
printf("%5d", v);
visited[v] = true;
queue<int> t;
t.push(v);
while (!t.empty())
{
v = t.front();
t.pop();
for (it = graph[v].begin(); it != graph[v].end(); ++it)
if (!visited[*it])
{
printf("%5d", *it);
t.p