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

来源:互联网 发布:淘宝免费送衣服是真的 编辑:程序博客网 时间:2024/06/04 00:06

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

Time Limit: 1000MS Memory Limit: 65536KB
SubmitStatistic Discuss

Problem 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的遍历结果。

Example Input

16 7 00 30 41 41 52 32 43 5

Example Output

0 3 4 2 5 1

Hint

用邻接表存储。

Author

#include <iostream>  #include <stdlib.h>  #include <stdio.h>  #include <string.h>  #include <queue>  #include <algorithm> using namespace std;  struct node  //边链表(横着) {      int v;      node *next;  };  struct VNode//表头节点表(竖着的) {int u;struct node *first;}pp[100];int visited[100],f=1;  int n,k,m;  int b[100],x[100];  void bfs(int t)  {      int q,k=0;      queue<int>Q;  //定义queue对象Q     Q.push(t);//入队,把t接到队列末端      visited[t]=1;      f=1;        while(!Q.empty())      {          q=Q.front(); //访问队头元素         Q.pop();  //         if(f)          {              f=0;              printf("%d",q);          }          else printf(" %d",q);          for(node *p=pp[q].first; p!=NULL; p=p->next)          {              if(visited[p->v]==0)              {                  Q.push(p->v);                  visited[p->v]=1;              }          }      }  }    int main()  {        int i,j;      int u,v,t;      scanf("%d",&n);      while(n--)      {          scanf("%d %d %d",&k,&m,&t);          //memset(head,NULL,sizeof(head));          memset(visited,0,sizeof(visited));          for(int i =0;i<m;i++)//初始化         {        pp[i].first = NULL;        }        for(i=0; i<m; i++)          {              scanf("%d %d",&u,&v);              struct node *p = (struct node *)malloc(sizeof( struct node));            p->v = v;            p->next = pp[u].first;            pp[u].first = p;            struct node *q = (struct node *)malloc(sizeof( struct node));            q->v = u;            q->next = pp[v].first;            pp[v].first = q;        }          int tt;          for(int i=0; i<m; i++)//边链表进行排序 (横着的)         {            struct node *p,*q;              for(p=pp[i].first; p; p=p->next)                  for(q=p->next; q; q=q->next)                  {                      if(p->v > q->v)                          swap(p->v,q->v);                  }          }         bfs(t);          printf("\n");      }      return 0;  }  


阅读全文
0 0
原创粉丝点击