BFS,这里的运行结果是各连通分量的顺序排列
#include<stdio.h>
#include<stdlib.h>
#define MAXV 10
typedef struct ANode
{
int adjvex;//该边的邻接节点编号
struct ANode* nextarc;//指向下一条边的指针
}ArcNode;//边界点的类型
typedef struct Vnode
{
char info;//顶点的其它信息
ArcNode* firstarc;//指向第一个边界点
}VNode;//邻接表的头节点类型
typedef struct {
VNode adlist[MAXV];//邻接表的头节点数组
int n, e;//图中的顶点数n和边数e
}AdjGraph;//完整的图邻接表类型
int visited[MAXV] = { 0 };
void Create(AdjGraph* G)
{
int j=0, k=0;
ArcNode* s;
scanf("%d %d", &G->n, &G->e);
for (int i = 0; i < G->n; i++)
{
scanf("%c", &G->adlist[i].info);
G->adlist[i].firstarc = NULL;
}
for (int i = 0; i < G->e; i++)
{
scanf("%d %d", &j, &k);
s = (ArcNode*)malloc(sizeof(ArcNode));
s->adjvex = k;
s->nextarc = G->adlist[j].firstarc;
G->adlist[j].firstarc = s;//头插法
}
}
void BFS(AdjGraph* G, int v)//广度优先算法
{
int front = 0, rear = 0;
VNode s[MAXV];//头节点数组
ArcNode *p;//指针数组
s[rear++] = G->adlist[v];
visited[v] = 1;
while(rear!=front)
{
printf("%c", s[front].info);
p = s[front++].firstarc;
while (p != NULL)
{
if (visited[p->adjvex] == 0)
{
visited[p->adjvex] = 1;
s[rear++] = G->adlist[p->adjvex];
}
p = p->nextarc;
}
;
}
}
void FindAllPath(AdjGraph* G)
{
for (int i = 0; i < G->n; i++)
{
if (visited[i] == 0)
{
BFS(G, i);
}
}
}
int main()
{
AdjGraph G;
Create(&G);
FindAllPath(&G);
return 0;
}
下面是运行结果