广度优先遍历2

题目描述

给定一个由 m 个顶点 n 条边构成的无向连通图,输出它的 BFS 序列。

要求:

  1. 起始顶点(每行 BFS 序列的起点)从小到大排列,即从 1 到 m 。
  2. 对同一顶点的多个邻接点,优先遍历编号较小的邻接点。

输入格式

第一行两个整数 m 和 n(0<m,n<100),分别为顶点数量和边的数量。

之后有 n 行数据,每行两个正整数,表示边的起点和终点对应的顶点编号。

每行的数据之间用空格隔开。

输出格式

输出共有 m 行,每行有 m 个整数,为题目要求的序列。

整数之间用 1 个空格分开,每行末尾最后一个数后有一个尾空格。

样例 #1

样例输入 #1

5 6
1 2
1 3
1 5
2 4
3 5
4 5

样例输出 #1

1 2 3 5 4
2 1 4 3 5
3 1 5 2 4
4 2 5 1 3
5 1 3 4 2
#include <iostream>
#include <cmath>
#include <algorithm>
#include <queue>
#include <map>
#include <set>
#include <stack>
#include <vector>
#include <cstring>
using namespace std;

int n,m;
bool vis[110];
vector<int>v[110];
queue<int>q;
void bfs(int s)
{
	q.push(s);
	vis[s]=true;
	while(q.size()>0)
	{
		int x=q.front();
		q.pop();
		cout<<x<<" ";
		for(int i=0;i<v[x].size();i++)
		{
			if(vis[v[x][i]]==0)
			{
				q.push(v[x][i]);
				vis[v[x][i]]=true;
			}
		}
	}
}
int main()
{
	cin>>n>>m;
	for(int i=1;i<=m;i++)
	{
		int x,y;
		cin>>x>>y;
		v[x].push_back(y);
		v[y].push_back(x);
	}
	for(int i=1;i<=n;i++)
		sort(v[i].begin(),v[i].end());
	for(int i=1;i<=n;i++)
	{
		memset(vis,0,sizeof(vis));
		bfs(i);
		cout<<endl;
	}
	return 0;
}

今天的博客十分好写,代码没啥大问题,只错了一个字母,就是输入的时候写成了i<=n……

就是一个正常的BFS,要sort是因为要求“优先遍历编号较小的邻接点”。

对了我代码实现的时候写的是n个顶点m条边(习惯性)。

  • 8
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值