//图的广度深度优先遍历
//说明: 采用邻接矩阵
//09.08.10
#include <iostream>
#include <vector>
#include <queue>
using namespace std;
//建立邻接矩阵
//visit标记节点是否已经被访问 , visit[x] = 1 表示已经被访问
//vertex保存节点
//将顶点个数保存在vertex[0] , 边的条数保存visit[0]
void CreateMatrix (vector<int> &visit , vector<int> &vertexes , int matrix[][100])
{
//输入节点个数
cout<<“input the number of the vertexes : “;
int ver_num; cin>>ver_num; vertexes[0] = ver_num;
//初始化节点
for (int i = 1 ; i <= ver_num; i++)
vertexes[i] = i;
//输入边的条数
cout<<“input the number of the edges : “;
int edge_num; cin>>edge_num; visit[0] = edge_num;
//邻接矩阵初始化
int x , y;
for (i = 0 ; i < edge_num; i++)
{
cin>>x>>y;
x– , y–;
matrix[x][y] = 1; matrix[y][x] = 1;
}
}
//广度优先遍历函数
void BFS (vector<int> visit , vector<int> vertexes ,int matrix[][100])
{
//输入遍历的开始节点
cout<<“BFS: input the node you want to begin : “;
int begin; cin>>begin;
cout<<begin<<ends; visit[begin] = 1;
queue<int> qu;
qu.push(begin);
//BFS核心代码
while (!qu.empty())
{
int t = qu.front() – 1;
for (int i = 0; i < vertexes[0]; i++)
{
int t1 = i +1;
if (matrix[t][i] == 1 && visit[t1] == 0)
{
cout<<t1<<ends; visit[t1] = 1;
qu.push(t1);
}
}
qu.pop();
}
cout<<endl;
}
//深度遍历递归函数
void Dfs (vector<int> &visit , vector<int> &vertexes , int matrix[][100] , int node)
{
cout<<node<<ends; visit[node] = 1;
//DFS核心代码
for (int i = 0; i < vertexes[0]; i++)
if (matrix[node-1][i] == 1 && visit[i+1] == 0)
Dfs (visit , vertexes , matrix , i+1);
}
//深度优先遍历函数
void DFS (vector<int> visit , vector<int> vertexes ,int matrix[][100])
{
cout<<“DFS: input the node you want to begin :”;
int begin ; cin>>begin;
Dfs (visit , vertexes , matrix , begin);
cout<<endl;
}
//主函数
int main ()
{
vector<int> visit(100); //访问向量,同时0号单元保存边的条数
vector<int> vertexes(100); //保存节点向量,同时0号单元保存节点的个数
int matrix[100][100] = {0}; //邻接矩阵保存边
CreateMatrix (visit , vertexes , matrix);
//输出邻接矩阵
for (int i = 0 ; i < vertexes[0] ; i++)
{
for (int j = 0 ; j < vertexes[0] ; j++)
cout<<matrix[i][j]<<ends;
cout<<endl;
}
//BFS : DFS
BFS(visit , vertexes , matrix);
DFS(visit , vertexes , matrix);
return 0;
}