E - 数据结构实验之图论二:基于邻接表的广度优先搜索遍历

Description

给定一个无向连通图,顶点编号从0到n-1,用广度优先搜索(BFS)遍历,输出从某个顶点出发的遍历序列。(同一个结点的同层邻接点,节点编号小的优先遍历)

Input

输入第一行为整数n(0< n <100),表示数据的组数。
对于每组数据,第一行是三个整数k,m,t(0<k<100,0<m<(k-1)*k/2,0< t<k),表示有m条边,k个顶点,t为遍历的起始顶点。 
下面的m行,每行是空格隔开的两个整数u,v,表示一条连接u,v顶点的无向边。

Output

输出有n行,对应n组输出,每行为用空格隔开的k个整数,对应一组数据,表示BFS的遍历结果。

Sample

Input

1
6 7 0
0 3
0 4
1 4
1 5
2 3
2 4
3 5

Output

0 3 4 2 5 1

Hint

用邻接表存储。

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
struct node{
    int data;
    struct node *next;
}*head[100], *p, *q;
int k;
int isbfs[100];
int queuebfs[100];
void sort(int k){
    int t;
    int i;
    for(i = 0; i < k; i++){
        for(p = head[i] -> next; p != NULL; p = p -> next){
            for(q = p -> next; q != NULL; q = q -> next){
                if(p -> data > q -> data){
                    t = p -> data;
                    p -> data = q -> data;
                    q -> data = t;
                }
            }
        }
    }
}
void bfs(int k){
    int in, out;
    int w;
    int i;
    in = out = 0;
    queuebfs[in++] = k;
    while(in > out){
        w = queuebfs[out++];
        for(p = head[w] -> next; p != NULL; p = p -> next){
            if(isbfs[p -> data] == 0){
                isbfs[p -> data] = 1;
                printf(" %d", p -> data);
                queuebfs[in++] = p -> data;
            }
        }
    }
}
int main(){
    int n;
    int m, t;
    int i;
    int u, v;
    scanf("%d", &n);
    while(n--){
        memset(isbfs, 0, sizeof(isbfs));
        memset(queuebfs, 0, sizeof(queuebfs));
        scanf("%d %d %d", &k, &m, &t);
        for(i = 0; i < k; i++){
            head[i] = (struct node *)malloc(sizeof(struct node));
            head[i] -> next = NULL;
        }
        for(i = 0; i < m; i++){
            scanf("%d %d", &u, &v);
            p = (struct node *)malloc(sizeof(struct node));
            p -> data = v;
            p -> next = head[u] -> next;
            head[u] -> next = p;
            q = (struct node *)malloc(sizeof(struct node));
            q -> data = u;
            q -> next = head[v] -> next;
            head[v] -> next = q;
        }
        sort(k);
        /*
        for(i = 0; i < k; i++){
            p = head[i] -> next;
            while(p != NULL){
                if(p -> next != NULL){
                    printf("%d ", p -> data);
                }
                else{
                    printf("%d\n", p -> data);
                }
                p = p -> next;
            }
        }
        */
        isbfs[t] = 1;
        printf("%d", t);
        bfs(t);
        printf("\n");
    }
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

程序员豪仔

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值