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

来源:互联网 发布:nginx 允许列出目录 编辑:程序博客网 时间:2024/06/05 23:42

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

Time Limit: 1000MS Memory Limit: 65536KB
Submit Statistic

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<bits/stdc++.h>   //万能头文件
using namespace std;
int b[105][105],visited[105];
int flag;
void BFS(int k,int t);    
int main()
{
    int n,i,k,m,t,u,v;
    cin>>n;
    while(n--)
    {
        cin>>k>>m>>t;
        memset(b,0,sizeof(b));
        memset(visited,0,sizeof(visited));
        for(i=0;i<m;i++)
        {
            cin>>u>>v;
            b[u][v]=b[v][u]=1;
        }
        flag=0;
        BFS(k,t);
        cout<<endl;
    }
    return 0;
}
void BFS(int k,int t)  //广度搜索
{
    int i;
    visited[t]=1;
    int temp;
    queue<int>q;
    q.push(t);
    while(!q.empty())
    {
        temp=q.front();
        q.pop();
        if(!flag)
        {
            flag=1;
            cout<<temp;
        }
        else
        {
            cout<<" "<<temp;
        }
        for(i=0;i<k;i++)
        {
            if(b[temp][i]&&!visited[i])
            {
                visited[i]=1;
                q.push(i);
            }
        }
    }
}

阅读全文
0 0