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

数据结构实验之图论一:基于邻接矩阵的广度优先搜索遍历
Time Limit: 1000 ms Memory Limit: 65536 KiB
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的遍历结果。
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<bits/stdc++.h>
using namespace std;
int gra[105][105]; //建立邻接矩阵存图
int que[200]; // 数组模拟队列
int in = 0, out = 0;// head  and  butt
int k, m, n;
bool visit[105];  // sign if node is visited
void bfs(int n) // bfs
{
    in = 0, out = 0;
    que[in++] = n;   // in queue
    while(in > out)  // queue is not empty
    {
        int now = que[out];
        out++;
        for(int i = 0; i < k; i++)// judge if it is node
        {
            if(!visit[i] && gra[now][i] == 1)
            {
                visit[i] = true; // visited is true
                que[in++] = i;// in queue
                cout <<" "<<i;
            }
        }
    }
}
int main()
{

    int t;
    int u, v;
    cin>>t;
    while(t--)
    {
        memset(visit,false,sizeof(visit));
        memset(gra,0,sizeof(gra));
        cin>>k>>m>>n;
        while(m--)
        {
            cin>>u>>v;
            gra[u][v] = gra[v][u] = 1;
        }
        cout << n;
        visit[n] = true;// 起始节点标记为true
        bfs(n);
        cout << endl;
    }
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值