广度优先遍历
输入顶点数据
输入边的信息
广度优先遍历结果如下
#include <iostream>
#include <queue>
#define MaxSize 10
using namespace std;
//边
typedef struct arc_node {
int adj_vex;//边对应节点在表中间的位置
struct arc_node *next_arc;//下一条边
} ArcNode;
//顶点
typedef struct v_node {
char data;
int tag; //用于标记该节点是否被访问
ArcNode *first_arc;//指向第一条边
} VNode;
typedef struct {
VNode list[MaxSize];//邻接表
int n, e;//节点个数和边数
} AGraph;
AGraph *InitGraph(int n, int e);
void CreateGraph(AGraph *graph);
void vision(VNode &node);
void BFS(AGraph *graph,int init_v);
int main() {
auto graph = InitGraph(5, 6);
CreateGraph(graph);
BFS(graph,0);
return 0;
}
AGraph *InitGraph(int n, int e) {
//初始化图的顶点和边的个数
auto graph = new AGraph;
graph->n = n;
graph->e = e;
return graph;
}
void CreateGraph(AGraph *graph) {
//创建节点表
char c;
for (int i = 0; i < graph->n; ++i) {
cin >> c;
graph->list[i].data = c;
graph->list[i].tag = 0;
graph->list[i].first_arc = nullptr;
}
//创建边
int vi, vj;
for (int i = 0; i < graph->e; ++i) {
cin >> vi >> vj;
auto arc = new ArcNode;
arc->adj_vex = vj;
//利用前插法进行边节点的插入
arc->next_arc = graph->list[vi].first_arc;
graph->list[vi].first_arc = arc;
}
}
void vision(VNode &node) {
node.tag = 1;
cout << node.data << endl;
}
void BFS(AGraph *graph, int init_v) {
queue<int> q;//用于放置顶点的索引
vision(graph->list[init_v]);
q.push(init_v);
int index;//记录队列第一个元素的索引
ArcNode *p;
while (!q.empty()) {
index = q.front();
q.pop();
p = graph->list[index].first_arc;
while (p) {
if (graph->list[p->adj_vex].tag != 1) {
q.push(p->adj_vex);
vision(graph->list[p->adj_vex]);
}
p = p->next_arc;
}
}
}