C语言实现邻接表的广度优先搜索

1. 对于图的遍历主要有两种遍历方式:深度优先遍历和广度优先遍历,对于图的遍历与树不同的是需要增加一个标记数组来对访问过的节点进行标记,假如访问过了我们就不能够再进行访问了

2. 下面是使用C语言实现广度优先遍历的过程:

① 首先需要存储一个图,下面使用的是邻接表的方式来存储图(使用邻接表来存储图在我的上一篇博客有写:https://blog.csdn.net/qq_39445165/article/details/92692027

② 对于广度优先搜索我们需要借助于队列来进行实现,具体的算法执行过程如下:

1)任取图中一个顶点进行访问,入队,并将这个顶点标记为已访问

2)当队列中不为空的时候循环执行:出队,依次检查出队顶点的所有邻接顶点,访问没有被访问过的邻接顶点并将其入队

3)当队列为空的时候循环结束,广度优先搜索结束

3. 下面是以邻接表为存储结构实现的的代码:

#include<stdio.h>
#include<iostream>
#define maxSize 10000
#include<malloc.h>
using namespace std;
typedef struct ArcNode{
	int adjvex;
	struct ArcNode *nextarc;
	int info;
}ArcNode; 

typedef struct{
	int data;
	ArcNode *firstarc;
}Vnode; 

typedef struct{
	Vnode adjlist[maxSize];
	int n, e;
}AGraph;

AGraph *graph;
//需要先进行初始化为0 
int visit[maxSize] = {0};
void  insertNode(ArcNode *node, ArcNode *newNode){
	ArcNode *p = node;
	while(p->nextarc != NULL){
		p = p->nextarc;
	}
	p->nextarc = newNode;	
}

void create(){
	graph = (AGraph*)malloc(sizeof(AGraph));
	cout << "输入顶点的数目: " << endl;
	cin >> graph->n;
	cout << "输入图中边的数目: " << endl;
	cin >> graph->e;
	int u = -1, v = -1, weight = -1;
	for(int i = 0; i < graph->n; i++){
		graph->adjlist[i].firstarc = NULL;
	}
	
	ArcNode *node; 
	for(int i = 0; i < graph->e; i++){
		cin >> u >> v >> weight;
		node = (ArcNode *)malloc(sizeof(ArcNode));
		node->adjvex = v; 
		node->info = weight;
		node->nextarc = NULL;
		graph->adjlist[u].data = u;
		if(graph->adjlist[u].firstarc == NULL){
			graph->adjlist[u].firstarc = node; 
		}else{
			insertNode(graph->adjlist[u].firstarc, node); 
		}	
	} 
}

void bfs(AGraph *G, int v){
	//使用到循环队列来进行处理 
	ArcNode *p;
	int que[maxSize], front = 0, rear = 0;
	int j;
	cout << v << " ";
	visit[v] = 1;
	rear = (rear + 1) % maxSize;
	que[rear] = v;
	while(front != rear){
		front = (front + 1) % maxSize;
		j = que[front];
		p = G->adjlist[j].firstarc;
		while(p != NULL){
			if(visit[p->adjvex] == 0){
				cout << p->adjvex << " ";
				visit[p->adjvex] = 1;
				rear = (rear + 1) % maxSize;
				que[rear] = p->adjvex;
			}
			p = p->nextarc;	
		}
	}	
}

int main(void){
	create();
	bfs(graph, 0);
	return 0;
} 

猜你喜欢

转载自blog.csdn.net/qq_39445165/article/details/92722764