数据结构实验图论一:基于邻接矩阵的广度优先搜索遍历

数据结构实验图论一:基于邻接矩阵的广度优先搜索遍历
Time Limit:1000MS     Memory Limit:65536KB     64bit IO Format:%lld & %llu

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

Sample Output

0 3 4 2 5 1

Hint

以邻接矩阵作为存储结构。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int n,m,k,t,i,j,s=0;
int q[101],vis[101];
int f[101];
int map[101][101];

void bfs(int x,int y)
{
    memset(vis,0,sizeof(vis));
    int jin=0,chu=0;
    q[jin++]=x;
    while(chu<jin)
    {
        i=q[chu++];
        for(j=0; j<y; j++)
        {
            if(map[i][j]==1)
            {
                q[jin++]=j;
                map[i][j]=0;
                map[j][i]=0;
            }
        }
        if(vis[q[chu]]==0)
          {
             f[s++]=q[chu];
             vis[q[chu]]=1;
          }
    }
}
int main()
{
    int a,b;
    scanf("%d",&n);
    while(n--)
    {
        scanf("%d%d%d",&k,&m,&t);
        for(i=0; i<m; i++)
        {
            scanf("%d%d",&a,&b);
            map[a][b]=1;
            map[b][a]=1;
        }
        bfs(t,k);
        printf("%d ",t);
        for(i=0; i<k-1; i++)
        {
            printf("%d",f[i]);
            if(i<k-2)
                printf(" ");
        }
        printf("\n");
    }
    return 0;
}

 

posted @ 2014-11-25 17:49  夏迩  阅读(200)  评论(0)    收藏  举报