因为图一般存储结构有两种:
邻接矩阵
邻接表
本文基于邻接矩阵实现图的广度优先遍历
这是我之前的博文,关于图的深度优先遍历(DFS)的递归实现和非递归实现
非递归实现(基于队列)
#include<iostream>
#include<queue>
#include<vector>
using namespace std;
#define MAX 20
#define START 1
int visited[MAX];
int map[MAX][MAX];
vector<char> vec;
void bfs(int start, int n)
{
queue<int> q;
int q_top;
cout << vec[start-1] << " ";
visited[start] = 1;
for (int i = 1; i <= n; i++)
{
if (map[start][i] == 1 && visited[i] == 0)
{
q.push(i);
visited[i] = 1;
}
}
while (!q.empty())
{
q_top = q.front();
q.pop();
cout << vec[q_top-1] << " ";
for (int i = 1; i <= n; i++)
{
if (map[q_top][i] == 1 && visited[i] == 0)
{
q.push(i);
visited[i] = 1;
}
}
}
cout << endl;
}
int main(int argc, int * argv[])
{
int num_vex, num_edge, x, y;
char c;
cout << "请输入图的全部结点(字符型式)" << endl;
while (cin >> c)
{
vec.push_back(c);
}
cin.clear();
cout << "请输入结点和弧的数量:" << endl;
cin >> num_vex >> num_edge;
for (int i = 0; i < MAX; i++)
{
for (int j = 0; j < MAX; j++)
{
map[i][j] = 0;
}
}
cout << "请输入每个弧的两个结点" << endl;
for (int i = 1; i <= num_edge; i++)
{
cin >> x >> y;
map[x][y] = map[y][x] = 1;
}
bfs(1, num_vex);
system("pause");
return 0;
}