//邻接矩阵的广度遍历算法

在这里插入图片描述

#include<stdio.h>
#include<stdlib.h>
#define MAXSIZE 20
#define MAXVEX 100//最大顶点数 

//----------------队列定义及函数------------
typedef struct{
	int data[MAXSIZE];
	int front;
	int rear;
}SqQueue;
//初始化 
bool InitQueue(SqQueue *Q){
	Q->front = 0;
	Q->rear = 0;
	return true;
}
//插入元素到队尾 
bool EnQueue(SqQueue *Q, int e){
	if((Q->rear + 1) % MAXSIZE == Q->front){
		return false;
	}
	Q->data[Q->rear] = e;
	Q->rear = (Q->rear + 1) % MAXSIZE;
	return true;
}
//删除元素到队头 
bool DeQueue(SqQueue *Q, int *e){
	if(Q->front == Q->rear){//循环队列为空 
		return false;
	}
	*e = Q->data[Q->front];
	Q->front = (Q->front + 1) % MAXSIZE;
	return true; 
} 
//返回当前队列的长度 
int QueueLength(SqQueue Q){
	return (Q.rear - Q.front + MAXSIZE) % MAXSIZE;
}

/*------------图的邻接矩阵定义及函数-----------*/ 
typedef int VertexType;//顶点类型 
typedef int EdgeType;
typedef struct{
	VertexType vexs[MAXVEX];//顶点表 
	EdgeType arc[MAXVEX][MAXVEX];//邻接矩阵 
	int numVertexes, numEdges;//图中当前顶点数和边数 
}MGraph;

//建立无向网图的邻接矩阵 
void CreateMGraph(MGraph *G){
	int i, j, k, w;
	char n;

	printf("输入顶点数和边数:\n");
	scanf("%d%d", &G->numVertexes, &G->numEdges);	
	//读入顶点信息,建立顶点表 
	for (i = 0; i < G->numVertexes; i++)
	{
		printf("请输入第%d个顶点的信息:",i+1);
		scanf("%d", &G->vexs[i]);
	}
	//邻接矩阵初始化 
	for(i = 0; i < G->numVertexes; i++){
		for(j = 0; j < G->numVertexes; j++){
			G->arc[i][j] = 0;
		}
	}
	//读入numEdges条边,建立邻接矩阵 
	for(k = 0; k < G->numEdges; k++){
		printf("输入边(vi, vj)上的下标i, 下标j:\n");
		scanf("%d%d", &i, &j);
		G->arc[i][j] = 1;
		G->arc[j][i] = G->arc[i][j];//无向图,矩阵对称 
	}		
}
//邻接矩阵的广度遍历算法 
void BFSTraverse(MGraph G, int visited[]){
	int i, j;
	int e;
	SqQueue Q;
	
	for(i = 0; i < G.numVertexes; i++){
		visited[i] = 0;
	}
	
	InitQueue(&Q);//初始化辅助用的队列
	for(i = 0; i < G.numVertexes; i++){//对每一个顶点做循环 
		if(! visited[i]){
			visited[i] = 1;
			printf("%d ", G.vexs[i]);
			EnQueue(&Q, i);
			
			while( QueueLength(Q) != 0){//当队列不为空,出队 
				DeQueue(&Q, &e);
				
				for(j = 0; j < G.numVertexes; j++){
					//查找其他未被访问过的邻接点
					if(G.arc[i][j] == 1 && !visited[j]){
						visited[j] = 1;
						printf("%d ", G.vexs[j]);
						EnQueue(&Q, j);//将找到的点入队列 
						
					} 
				}
			}
		}
	} 
}

int main(){
	MGraph G;	
	CreateMGraph(&G);
	
	int visited[G.numVertexes];//访问标志的数组 
	BFSTraverse(G, visited);
	
}
  • 3
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值