邻接矩阵:
#include <stdio.h>
#define MAXV 10
#define INF 0
int n=5,G[MAXV][MAXV]={ { 0, 1, 1, 0, 0 },
{ 0, 0, 1, 1, 0 },
{ 0, 1, 1, 1, 0 },
{ 1, 0, 0, 0, 0 },
{ 0, 0, 1, 1, 0 } };
int vis[MAXV]={0};
void BFS(int v){
vis[v]=1;
printf("%d ",v+1);
int queue[MAXV]={0},front=0,rear=-1;
queue[++rear]=v;
while(front<=rear){
v=queue[front++];
for(int u=0;u<n;u++){
if(vis[u]==0&&G[v][u]!=INF){
queue[++rear]=u;
vis[u]=1;
printf("%d ",u+1);
}
}
}
}
void BFSTrave(){
for(int i=0;i<n;i++){
if(vis[i]==0){
BFS(i);
// putchar('\n');
}
}
}
int main(){
BFSTrave();
return 0;
}
邻接表:
#include <stdio.h>
#define MAXV 10
typedef struct ArcNode{
int adjvex;
struct ArcNode *next;
}ArcNode;
typedef struct VNode{
int data;
ArcNode *first;
}VNode,AdjList[MAXV];
typedef struct {
int arcnum,vexnum;
AdjList list;
}ALGraph;
ALGraph G;
int vis[MAXV]={0};
void BFS(int v){
int queue[MAXV]={0},front=0,rear=-1;
ArcNode *p;
vis[v]=1;
printf("%d ",v+1);
queue[++rear]=v;
while(front<=rear){
v=queue[front++];
p=G.list[v].first;
while(p){
int u=p->adjvex;
if(vis[u]==0){
queue[++rear]=u;
vis[u]=1;
printf("%d ",u+1);
}
p=p->next;
}
}
}
void BFSTrave(){
for(int i=0;i<G.vexnum;i++){
if(vis[i]==0){
BFS(i);
}
}
}
int main(){
BFSTrave();
return 0;
}