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

Time Limit: 1000MSMemory Limit: 65536KB

SubmitStatistic

ProblemDescription

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

Input

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

Output

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

ExampleInput

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

ExampleOutput

0 3 4 2 5 1

Hint

以邻接矩阵作为存储结构。

Author

#include <iostream>
#include<bits/stdc++.h>
int map1[222][222],vis[222],ans[222];
int top;
using namespace std;
void bfs(int t,int n)
{
    queue<int>q;
    vis[t] = 1;
    ans[top++] = t;
    q.push(t);
    while(!q.empty())
    {
        int v = q.front();
        q.pop();
        for(int i=0;i<n;i++)
        {
            if(!vis[i]&&map1[v][i]==1)
            {
            q.push(i);
            vis[i] = 1;
            ans[top++] = i;
            }

        }
    }
}
int main()
{
    int t,k,m,u,v,y;
    scanf("%d",&y);
    while(y--)
    {
        cin>>k>>m>>t;
        memset(map1,0,sizeof(map1));
        memset(vis,0,sizeof(vis));
        for(int i=0; i<m; i++)
        {
            cin>>v>>u;
            map1[v][u]=map1[u][v] = 1;
        }
        top = 0;
        bfs(t,k);
        for(int i=0; i<top-1; i++)
        {
            printf("%d ",ans[i]);
        }
        printf("%d\n",ans[top-1]);
    }
    return 0;
}


/***************************************************
User name: jk160505徐红博
Result: Accepted
Take time: 0ms
Take Memory: 352KB
Submit time: 2017-02-15 10:49:09
****************************************************/