//图的广度深度优先遍历
//说明: 采用邻接表存储
//顶点表由结构体构成,结构体包括顶点,visit(该节点是否被访问过),邻接点指针
//09.8.9
//09.8.10修改(增加DFS)
#include <iostream>
#include <vector>
#include <queue>
using namespace std;
//邻接点结构体
struct Node
{
int vertex;
Node *next;
Node ():next(NULL){}
};
//节点表结构体
struct Ver_tab
{
int vertex;
int visit ;
Node *next;
Ver_tab ():visit(0),next(NULL) {}
};
//建立邻接表
void CreateTable (vector<Ver_tab> &ver_table)
{
//分两步
//第一,建立节点表
int ver_num;
cout<<“input the number of the vertexes : “; cin>>ver_num;
ver_table[0].vertex = ver_num; //节点个数放在表头vertex位置
for (int i = 1; i <= ver_num; i++)
ver_table[i].vertex = i;
//第二,增加邻接节点
int edge_num; //边的条数
cout<<“input the number of the edges : “; cin>>edge_num;
ver_table[0].visit = edge_num; //边的条数放在表头visit位置
int a1 , a2;
for (i = 0; i < edge_num; i++)
{
cin>>a1>>a2;
//点a2后面增加一个邻接点a1
Node * node1 = new Node;
node1->vertex = a1;
node1->next = ver_table[a2].next;
ver_table[a2].next = node1;
//点a1后面增加二个邻接点a2
Node * node2 = new Node;
node2->vertex = a2;
node2->next = ver_table[a1].next;
ver_table[a1].next = node2;
}
}
//广度优先遍历
void BFS (vector<Ver_tab> ver_table)
{
cout<<“input the position you want to begin : “;
int begin; cin>>begin;
queue<int> qu;
qu.push (begin);
cout<<qu.front()<<ends; ver_table[begin].visit = 1;
while (!qu.empty())
{
int tmp = qu.front();
//BFS核心代码
for (Node *p = ver_table[tmp].next; p != NULL ; p = p->next)
{
int vertex = p->vertex;
if (ver_table[vertex].visit == 0)
{
cout<<vertex<<ends; ver_table[vertex].visit = 1;
qu.push (vertex);
}
}
qu.pop();
}
cout<<endl;
}
//深度遍历递归函数
void Dfs (vector<Ver_tab> &ver_table , int vertex)
{
//DFS核心代码
cout<<vertex<<ends; ver_table[vertex].visit = 1;
for (Node *p = ver_table[vertex].next ; p != NULL; p = p->next)
if (ver_table[p->vertex].visit == 0)
Dfs (ver_table , p->vertex);
}
//深度优先遍历(递归实现)
void DFS (vector<Ver_tab> ver_table)
{
cout<<“DFS: input the position you want to begin : “;
int begin; cin>>begin;
Dfs (ver_table , begin);
cout<<endl;
}
//主函数
int main ()
{
vector<Ver_tab> ver_table(1000);
CreateTable (ver_table);
BFS (ver_table);
DFS (ver_table);
return 0;
}