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

    xiaoxiao2025-11-01  7

    题目描述

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

    输入

    输入第一行为整数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顶点的无向边。

    输出

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

    示例输入

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

    示例输出

    0 3 4 2 5 1

    提示

    用邻接表存储。

    #include <iostream> #include <cstdio> #include <queue> #include <cstring> #include <cstdlib> using namespace std; struct node {    int data;    struct node*next; }; struct node*head[150]; int i,vis[150],w; void bfs(int k,int m,int t) {   struct node*p;     queue<int>q;     printf("%d",t);     q.push(t);     while(!q.empty())     {         w=q.front();         q.pop();         for(p=head[w]->next;p;p=p->next)//以元素做下标后面连着他的后继元素         {             if(!vis[p->data])             {                printf(" %d",p->data);                vis[p->data]=1;                q.push(p->data);             }         }

        } } int main() {     int n,k,m,t,u,v,nu;     struct node*p,*q;     scanf("%d",&n);     while(n--)     {        scanf("%d%d%d",&k,&m,&t);        memset(vis,0,sizeof(vis));        for(i=0;i<k;i++)        {            head[i]=(struct node*)malloc(sizeof(struct node));            head[i]->next=NULL;        }        for(i=0;i<=m-1;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;            p=(struct node*)malloc(sizeof(struct node));            p->data=u;            p->next=head[v]->next;            head[v]->next=p;//元素u的后面跟的都是他所连得元素        }        for(i=0;i<=k-1;i++)        {            for(p=head[i]->next;p;p=p->next)//优先遍历小节点             for(q=p->next;q;q=q->next)            {                if(p->data>q->data)//这是链表如果对整个结构体进行交换指针就乱了                {                   nu=p->data;                   p->data=q->data;                   q->data=nu;                }            }        }        vis[t]=1;        bfs(k,m,t);     }     return 0; }

     

    转载请注明原文地址: https://ju.6miu.com/read-1303732.html
    最新回复(0)