思路:依次遍历每一个结点,把该结点加入队列,同时把该结点未被遍历的相邻结点也加入队列中,就这样一直搜索,直到再也无法找到未被遍历的结点,算法结束,退出。
#include<stdio.h>
#include<stdlib.h>
#define MAXNUM 100
typedef struct DAG {
char vt [MAXNUM];
int vertex[MAXNUM][MAXNUM];
int vm;
} CG;
typedef struct node {
char vertex;
struct node * next;
} ND;
int getindex(char v0,char vt[],int n);
void add(ND * head,ND * tail,char vertex,ND * res[]);
ND * del(ND * head);
void BFS(int vertex[][100],int visited[],int vm,char v0,char vt[]);
int main() {
CG graph;
scanf("%d",&graph.vm);
int i = 0,j = 0;
int visited[10] = {0};
char ch = '\0';
ch = getchar();
for(i = 0; i < graph.vm; i++) {
scanf("%c",&graph.vt[i]);
ch = getchar();
}
for(i = 0; i < graph.vm; i++) {
for(j = 0; j < graph.vm; j++) {
scanf("%d",&graph.vertex[i][j]);
}
}
printf("\n广度优先搜索:\n");
BFS(graph.vertex,visited,graph.vm,'b',graph.vt);
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[]) {
ND * newnode = (ND *)malloc(sizeof(ND));
newnode->vertex = vertex;
if(head == NULL) {
head = newnode;
tail = newnode;
} else {
tail->next = newnode;
tail = newnode;
}
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(int vertex[][100],int visited[],int vm,char v0,char vt[]) {
int i = 0,j = 0;
int index = 0;
int size = 0;
ND * res[2];
ND * head = NULL,* tail = NULL;
add(head,tail,v0,res);
index = getindex(v0,vt,vm);
if (index == -1) {
printf("结点不存在!");
return;
}
visited[index] = 1;
size++;
head = res[0];
tail = res[1];
while(size != 0) {
index = getindex(head->vertex,vt,vm);
if (index == -1) {
printf("结点不存在!");
return;
}
for(j = 0; j < vm; j++) {
if(vertex[index][j] == 1 && visited[j] == 0) {
add(head,tail,vt[j],res);
visited[j] = 1;
size++;
head = res[0];
tail = res[1];
}
}
head = del(head);
size--;
printf("%c ",vt[index]);
if (size != 0) printf("->");
}
}
广度优先搜索 — C语言非递归版
最新推荐文章于 2022-03-04 11:24:52 发布