邻接表的bfs遍历

//输入样例
/*
5 0
AB AD AC CD BE DE
*/
//输出
/*
A  1  2  3
B  0  4
C  0  3
D  0  2  4
E  1  3
*/
//dfs测试数据
/*
8 0
Please Input the edge x-->y:AB AC BD BE DH EH HF HG FC GC CA
A  1  2  2
B  0  3  4
C  0  0  5  6
D  1  7
E  1  7
F  2  7
G  2  7
H  3  4  5  6
ABDHEFCG
*/
#include<iostream>
#include<cstdio>
using namespace std;
#define MAXVER 10
int visited[MAXVER];
typedef char Elemtype;
//接下来要连的结点
typedef struct node{
int num;
struct node *next;
//首结点数组
typedef struct{
struct{
Elemtype vertex;
}ve[MAXVER];
int vex,edge,tag;
//使用简单结构建立图的邻接表
{
G->vex=n;
G->tag=m;
int e=0;
for(int i=0;i<n;i++){
G->ve[i].vertex='A'+i;
G->ve[i].first=NULL;
}
Elemtype x,y;
scanf("%c%c",&x,&y);
while(x!=' '&&y!=' ')
{
e++;
s->num=y-'A';
if(G->ve[x-'A'].first==NULL){
G->ve[x-'A'].first=s;
s->next=NULL;
}
else{
p=G->ve[x-'A'].first;
if(p->num>s->num){
s->next=p;
G->ve[x-'A'].first=s;
}
else{
q=p->next;
while(q!=NULL&&q->num<s->num)
{
p=q;
q=q->next;
}
p->next=s;
s->next=q;
}
}
if(!G->tag)
{
s->num=x-'A';
if(G->ve[y-'A'].first==NULL) {G->ve[y-'A'].first=s;s->next=NULL;}
else{
p=G->ve[y-'A'].first;
if(p->num>s->num)
{s->next=p;G->ve[y-'A'].first=s;}
else{
q=p->next;
while(q!=NULL&&q->num<s->num) {p=q;q=q->next;}
p->next=s;
s->next=q;
}
}
}
getchar();
scanf("%c%c",&x,&y);
}
G->edge=e;
}
//输出用邻接表表示的图的算法
{
for(int i=0;i<G->vex;i++)
{
p=G->ve[i].first;
printf("%c",G->ve[i].vertex);
while(p)
{
printf("%3d",p->num);
p=p->next;
}
printf("\n");
}
}
{
int queue[MAXVER];
int front,rear,i;
front=rear=0;
queue[rear++]=v;
while(front!=rear)
{
v=queue[front++];
visited[v]=1;
printf("%c",G->ve[v].vertex);
p=G->ve[v].first;
while(p)
{
for(i=0;i<rear;i++)
if(p->num==queue[i]) break;
if(i>=rear)
queue[rear++]=p->num;
p=p->next;
}
}
}
{
for(int i=0;i<G->vex;i++)
if(!visited[i]) bfs(G,i);
}
int main()
{
int n,m;
scanf("%d%d",&n,&m);
getchar();
cregraph(G,n,m);
list(G);
bfsgraph(G);
printf("\n");
return 0;
}

• 广告
• 抄袭
• 版权
• 政治
• 色情
• 无意义
• 其他

120