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

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

Time Limit: 1000 ms Memory Limit: 65536 KiB

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

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

用邻接表存储。

Source

#include <iostream>
#include<queue>
#include<cstring>
#include<algorithm>
using namespace std;
int p;
int a[101],b[101];
int e[101][101];
//e存储矩阵,tag存储标识符(遍历过为1,初始为0)
//a存储遍历后得到的数组
//b是标记已经遍历过的结点
void BFS(int n,int k)
{
    p=0;
    a[p++]=k;
    b[k]=1;
    queue<int>q;
    q.push(k);
    while(!q.empty())
    {
        int v=q.front();
        q.pop();
        for(int i=0; i<n; i++)
        {
            if(b[i]==0&&e[v][i]==1)
            {
                a[p++]=i;
                b[i]=1;
                q.push(i);
            }
        }
    }
}
int main()
{
    int t;
    cin>>t;
    while(t--)
    {
        int n,m,k;
        memset(a,0,sizeof(a));
        memset(b,0,sizeof(b));
        cin>>n>>m>>k;
        for(int i=0; i<m; i++)
        {
            int x,y;
            cin>>x>>y;
            e[x][y]=1;
            e[y][x]=1;
            //因为为无向图,所以要左右标记
        }
        BFS(n,k);
        cout<<a[0];
        for(int i=1; i<n; i++)
        {
            cout<<" "<<a[i];
        }
        cout<<endl;
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_41374539/article/details/81666659
今日推荐