# 图的遍历 C++

``````#include <iostream>
#include <queue>
using namespace std;

const int MaxSize = 5;
template <class T>
class MGraph
{
public:
MGraph(T a[], int b[][MaxSize], int n, int e);        //构造函数，建立具有n个顶点e条边的图
void dfsTraverse(int v);        //深度优先遍历图
void bfsTraverse(int v);        //广度优先遍历图
private:
T vertex[MaxSize];              //存放图中顶点的数组
int arc[MaxSize][MaxSize];      //存放图中边的数组
int vertexNum, arcNum;          //图的顶点数和边数
int visited[MaxSize];           //有没访问数组
queue<int> que;
};

template <class T>
MGraph<T>::MGraph(T a[], int b[][MaxSize], int n, int e)
{
vertexNum = n; arcNum = e;
for (int i = 0; i<vertexNum; i++)
{
vertex[i] = a[i];
visited[i] = 0;
}
for (int i = 0; i<vertexNum; i++)             //直接放入邻接矩阵
for (int j = 0; j<vertexNum; j++)
arc[i][j] = b[i][j];
}

template <class T>
void MGraph<T>::dfsTraverse(int v)                //深度优先
{
cout << vertex[v] << " ";                       //访问一次，标记已被访问过
visited[v] = 1;
for (int j = 0; j<vertexNum; j++)
if (arc[v][j] == 1 && visited[j] == 0)       //存在此边，且没被访问过
dfsTraverse(j);
}

template <class T>
void MGraph<T>::bfsTraverse(int v)                //广度优先
{
for (int i = 0; i<vertexNum; i++)
{
visited[i] = 0;
}
cout << vertex[v] << " ";                       //访问一次，标记已被访问过
visited[v] = 1;
que.push(v);                                //被访问顶点入队
while (que.empty() != 1)
{
v = que.front();                        //队头元素出队放入v中
que.pop();
for (int j = 0; j<vertexNum; j++)
if (arc[v][j] == 1 && visited[j] == 0)           //判断是否有边，且顶点有没有别访问过
{
cout << vertex[j] << " ";
visited[j] = 1;
que.push(j);
}
}
}

void main()
{
char a[5] = { 'A','B','C','D','E' };                          //邻接矩阵
int b[5][5] = {
0,1,0,1,0,
1,0,1,0,1,
0,1,0,1,1,
1,0,1,0,0,
0,1,1,0,0, };

MGraph<char> GM(a, b, 5, 6);

cout << "广度优先遍历:" << endl;
GM.bfsTraverse(0);                                          //从A开始访问
cout << endl;

MGraph<char> GM2(a, b, 5, 6);
cout << "深度优先遍历:" << endl;
GM2.dfsTraverse(0);                                          //从A开始访问
cout << endl;
}``````

原文作者：数据结构之图
原文地址: https://blog.csdn.net/A13155283231/article/details/53293509
本文转自网络文章，转载此文章仅为分享知识，如有侵权，请联系博主进行删除。