#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);
}
广度优先搜索 ---- C语言递归版
最新推荐文章于 2025-03-21 00:00:00 发布