图的广度优先遍历(C语言)

本实验实现邻接表表示下无向图的广度优先遍历。

程序的输入是图的顶点序列和边序列(顶点序列以*为结束标志,边序列以-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;  
 }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值