如果说深度优先搜索是类似于树的前序遍历,而广度优先搜索类似于树的层序遍历。
如图一所示,先建立一个普通的图,在转变成类似于树的格式。
然后给每个顶点都赋予下标,可以看见有9个顶点,15条边。
在代码中我们采队列来实现BFS。
指定从A开始遍历,A入队列,遍历A的所有邻接顶点,分别是B与F
,此后发现A的邻接顶点都遍历完了,A出队列。开始对B进行相同的操作,重复此过程。
接下来是代码片段
//队列定义方法
#include <stdio.h>
#define MAX_QUEUE_SIZE 100
typedef struct {
int data[MAX_QUEUE_SIZE];
int front;
int rear;
} Queue;
// 初始化队列
void initQueue(Queue* q) {
q->front = -1;
q->rear = -1;
}
// 检查队列是否为空
int isEmpty(Queue *q) {
return (q->front == -1);
}
// 入队操作
void enqueue(Queue* q, int item) {
if (q->rear == MAX_QUEUE_SIZE - 1) {
printf("Queue is full. Cannot enqueue.\n");
return;
}
if (isEmpty(q)) {
q->front = 0;
}
q->rear++;
q->data[q->rear] = item;
}
// 出队操作
void dequeue(Queue* q) {
int item;
if (isEmpty(q)) {
printf("Queue is empty. Cannot dequeue.\n");
return -1; // 返回一个错误值
}
item = q->data[q->front];
if (q->front == q->rear) {
q->front = -1;
q->rear = -1;
}
else {
q->front++;
}
}
邻接矩阵的广度优先搜索
#include <stdio.h>
#include <stdlib.h>
typedef char VertexType;//顶点类型
typedef int EdgeType;//边上的权值
#define MAXVEX 100
#define INFINITY 65535 //65535代表无穷大
#define TRUE 1
#define FALSE 0
typedef int Boolean;
Boolean visited[MAXVEX];
typedef struct
{
VertexType vexs[MAXVEX]; //顶点表
EdgeType arc[MAXVEX][MAXVEX];//邻接矩阵
int numVertexes, numEdges; //顶点数以及边数
}MGraph;
void CreateMGraph(MGraph* G)
{
int i, j, k, w;
printf("输入顶点数和边数:\n");
scanf("%d%d", &G->numVertexes, &G->numEdges);
printf("请输入顶点信息:");
getchar();
for (i = 0; i < G->numVertexes; i++)//分别输入顶点信息
{
scanf("%c", &G->vexs[i]);
getchar();
}
for (i = 0; i < G->numVertexes; i++)
for (j = 0;j < G->numVertexes; j++)
G->arc[i][j] = INFINITY; //初始化所有点之间权无穷大
for (k = 0; k < G->numEdges; k++)
{
printf("输入边(vi,vj)上的下标i,下标j和权w:\n");
scanf("%d%d%d", &i, &j, &w);
G->arc[i][j] = w;
G->arc[j][i] = G->arc[i][j];//无向图,矩阵对称
}
}
//邻接矩阵的深度优先操作
void DFS(MGraph G, int i)
{
int j;
visited[i] = TRUE;
printf("%c", G.vexs[i]); //打印顶点
for (j = 0; j < G.numVertexes; j++)
{
if (G.arc[i][j] == 1 && !visited[j])
DFS(G, j); //对未访问的邻接顶点进行访问
}
}
//邻接矩阵的深度遍历操作
void DFSTraverse(MGraph G)
{
int i;
for (i = 0; i < G.numVertexes; i++)
visited[i] = FALSE; //初始化所有顶点都为未访问
for (i = 0; i < G.numVertexes; i++)
if (!visited[i]) //从创造的邻接矩阵中第一行开始遍历
DFS(G, i);
}
//邻接矩阵的广度优先搜索
void BFSTraverse(MGraph G)
{
int i,j;
Queue Q;
for (i = 0; i < G.numVertexes; i++)
visited[i] = FALSE;
initQueue(&Q); //初始化一辅助用的队列
for (i = 0; i < G.numVertexes;i++)
{
if (!visited[i])
{
visited[i] = TRUE; //访问后赋值为真
enqueue(&Q, i); //对访问的元素进行入队操作
printf("%c", G.vexs[i]);//打印顶点
while (!isEmpty(&Q))
{
dequeue(&Q);
for (j = 0; j < G.numVertexes; j++)
{
if (G.arc[i][j] == 1 && !visited[j])
{
visited[j] = TRUE;
enqueue(&Q, j);
printf("%c", G.vexs[j]);//继续访问
}
}
}
}
}
}
int main()
{
MGraph G;
CreateMGraph(&G);
BFSTraverse(G);
return 0;
}
执行结果图