本实验实现邻接表表示下无向图的广度优先遍历。
程序的输入是图的顶点序列和边序列(顶点序列以*为结束标志,边序列以-1,-1为结束标志)。程序的输出为图的邻接表和广度优先遍历序列。例如:
程序输入为:
a
b
c
d
e
f
*
0,1
0,4
1,4
1,5
2,3
2,5
3,5
-1,-1
程序的输出为:
the ALGraph is
a 4 1
b 5 4 0
c 5 3
d 5 2
e 1 0
f 3 2 1
the Breadth-First-Seacrh list:aebfdc
样例
输入(1)
a
b
c
d
e
f
*
0,1
0,4
1,4
1,5
2,3
2,5
3,5
-1,-1
输出(1)
the ALGraph is
a 4 1
b 5 4 0
c 5 3
d 5 2
e 1 0
f 3 2 1
the Breadth-First-Seacrh list:aebfdc
代码
#include<stdio.h>
#include<stdlib.h>
struct node{
char d;
int dnum;
int visit;
int chain[200];
}list[200];
void bfs(int find)
{
int after[200],afnum=0,i,get;
if(list[find].visit==0)
{
printf("%c",list[find].d);
list[find].visit=1;
}
for(i=list[find].dnum-1;i>=0;i--)
{
get=list[find].chain[i];
if(list[get].visit==0)
{
after[afnum]=get;
afnum++;
printf("%c",list[get].d);
list[get].visit=1;
}
}
for(i=0;i<afnum;++i)
{
bfs(after[i]);
}
}
int main(){
char c;
int n=0,a,b;
do
{
c=getchar();
getchar();
if(c!='*')
{
list[n].d=c;
list[n].dnum=0;
list[n].visit=0;
n++;
}
else break;
}while(1);
while(1)
{
scanf("%d,%d",&a,&b);
if(a==-1&&b==-1) break;
else
{
list[a].chain[list[a].dnum]=b;
list[a].dnum++;
list[b].chain[list[b].dnum]=a;
list[b].dnum++;
}
}
printf("the ALGraph is\n");
for(int i=0;i<n;i++)
{
printf("%c",list[i].d);
for(int j=list[i].dnum-1;j>=0;j--)
{
printf(" %d",list[i].chain[j]);
}
printf("\n");
}
printf("the Breadth-First-Seacrh list:");
for(int i=0;i<n;i++)
{
if(list[i].visit==0)
{
bfs(i);
}
}
printf("\n");
return 0;
}