6-5 图的广度遍历-邻接表实现 (10分)_数据结构实验6_羊卓的杨

6-5 图的广度遍历-邻接表实现 (10分)

函数接口定义:

void BFS(ALGraph *G,int i);

其中ALGraph是邻接表存储的图,定义如下:

#define MAX_VERTEX_NUM 10 /定义最大顶点数/
typedef int Vertex;
typedef struct ArcNode{ /表结点/
int adjvex; /邻接点域/
struct ArcNode *nextarc; /指向下一个表结点/
}ArcNode;
typedef struct VNode{ /头结点/
Vertex data; /顶点域/
ArcNode *firstarc; /指向第一个表结点/
}VNode,AdjList[MAX_VERTEX_NUM]; /AdjList是数组类型/
typedef struct {
AdjList vertices; /邻接表中数组定义/
int vexnum,arcnum; /图中当前顶点数和边数/
} ALGraph; /图类型/

裁判测试程序样例:

#include"stdio.h"
#include"stdlib.h"
#define MAX_VERTEX_NUM 10      /*定义最大顶点数*/
typedef int Vertex;
typedef struct  ArcNode{       /*表结点*/
    int adjvex;               /*邻接点域*/
    struct  ArcNode *nextarc; /*指向下一个表结点*/
}ArcNode;
typedef struct VNode{           /*头结点*/
    Vertex data;                  /*顶点域*/
    ArcNode *firstarc;          /*指向第一个表结点*/
}VNode,AdjList[MAX_VERTEX_NUM]; /*AdjList是数组类型*/
typedef struct { 
    AdjList vertices;           /*邻接表中数组定义*/
    int vexnum,arcnum;          /*图中当前顶点数和边数*/
} ALGraph;                 /*图类型*/
typedef enum{FALSE,TRUE} Boolean;
Boolean visited[MAX_VERTEX_NUM];/*定义标志向量,为全局变量*/
void CreatALGraph(ALGraph *G);/* 创建图并且将Visited初始化为false;裁判实现,细节不表 */
void BFS(ALGraph *G,int v);
int main()
{
    Vertex v;
    ALGraph G;
    CreatALGraph(&G);
    scanf("%d", &v);
    printf("BFS from %d:",v);
    BFS(&G,v);     
    return 0;
}
/* 你的代码将被嵌在这里 */

在这里插入图片描述

输入样例:

5

输出样例:

BFS from 5: 5 1 2 4 6 3 0

答案样例

int q[1000], front, rear;//依然是双指针加数组模仿队列
void BFS(ALGraph *G,int i) {//创作不易,点个赞吧,新春快乐~
	q[rear++] = G->vertices[i].data;
	visited[G->vertices[i].data] = TRUE;
	while(rear > front) {
		int x = q[front];
		printf(" %d", q[front++]);//输出一个front就++一下
		while(G->vertices[x].firstarc!=NULL) {
			if(G->vertices[x].firstarc!=NULL && visited[G->vertices[x].firstarc->adjvex]==FALSE) {
				q[rear++] = G->vertices[x].firstarc->adjvex;
				visited[G->vertices[x].firstarc->adjvex] = TRUE;
			}
			G->vertices[x].firstarc = G->vertices[x].firstarc->nextarc;
		}
	}
}

感谢你的点赞❤⭐
哔哩哔哩/bilibili:羊卓的杨
公众号:羊卓的杨

  • 6
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值