广度优先搜索 ---- C语言递归版

#include<stdio.h>
#include<stdlib.h>
#define MAX 100
//图结构
typedef struct dj {
int vn;
char vertex[MAX];
int edge[MAX][MAX];
} DJ;
//图顶点
typedef struct node {
char vertex;
struct node * next;
} ND;
//最短路径
typedef struct {
int dist[MAX][MAX];
char route[MAX][MAX];
} RT;

ND * head = NULL;
ND * tail = NULL;
ND * res[2] = {NULL};

//主函数
int getindex(char v0,char vt[],int n);
void add(ND * head,ND * tail,char vertex,ND * res[]);
ND *del(ND *head);
void BFS(DJ graph,char v0,char vt[],int visited[]);
int main() {
DJ graph;
scanf("%d",&graph.vn);
char temp = '\0';
int visited[MAX] = {0};
temp = getchar();
int i = 0,j = 0;

for(i = 0; i < graph.vn; i++) {
	scanf("%c",&graph.vertex[i]);
	temp = getchar();
}

for(i = 0; i < graph.vn; i++) {
	for(j = 0; j < graph.vn; j++) {
		scanf("%d",&graph.edge[i][j]);
	}
}
BFS(graph,'a',graph.vertex,visited);
return 0;
}
//获得顶点的下标
int getindex(char v0,char vt[],int n) {
int i = 0;
for(i = 0; i < n; i++) {
	if(v0 == vt[i]) {
		return i;
	}
}
return -1;
}
//在队列末尾增加顶点
void add(ND * head,ND * tail,char vertex,ND * res[]) {
if(head == NULL) {
	head = (ND*) malloc(sizeof(ND));
	head->vertex = vertex;
	tail = head;
	tail->next = NULL;
} else {
	tail->next = (ND*) malloc(sizeof(ND));
	tail = tail->next;
	tail->next = NULL;
	tail->vertex = vertex;
}
res[0] = head;
res[1] = tail;
}
//删除队列顶点
ND *del(ND *head) {
ND * temp;
temp = head;
head = head->next;
free(temp);
temp = NULL;
return head;
}
//递归进行宽度优先搜索
void BFS(DJ graph,char v0,char vt[],int visited[]) {
if(head == NULL) {
	add(head,tail,v0,res);
	head = res[0];
	tail = res[1];
}
int i = 0;
int index = 0;
index = getindex(v0,vt,graph.vn);
for(i = 0; i < graph.vn; i++) {
	if(graph.edge[index][i] == 1&&visited[i] == 0) {
		add(head,tail,graph.vertex[i],res);
		head = res[0];
		tail = res[1];
		visited[i] = 1;
	}
}

head = del(head);
if(head != NULL) printf("%c->",v0);
else printf("%c",v0);
visited[index] = 1;
if(head != NULL) BFS(graph,head->vertex,vt,visited);
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值