【入门】图的bfs遍历

描述

一个有n个结点的无向连通图,这些结点以编号:1、2、……n进行编号,现给出结点间的连接关系。请以结点1为起点,按广度优先搜索(bfs)、优先访问小编号结点的顺序遍历并输出该图。

输入描述

第一行为两整数,n和e,表示n个顶点,e条边;(2<=n,e<=10)

以下e行每行两个数,表示两个结点是联通的。

输出描述

只有一行,为节点按照广度优先、小编号结点优先访问的结果。

用例输入 1 
5 7
1 2
1 3
1 4
2 4
2 5
3 5
4 5
用例输出 1 
1 2 3 4 5
来源

图论 图的遍历

code:

#include<iostream>
#include<stdio.h>
#include<vector>
#include<queue>
using namespace std;
int n, m;
vector<int> g[100005];
bool vis[100005];
void bfs(int idx) {
	queue<int> q;
	int cnt = 0;
	q.push(idx);
	while (!q.empty() && cnt < n) {
		int t = q.front();
		if (!vis[t]) {
			cout << t << ' ';
			cnt++;
			vis[t] = 1;
		}
		for (auto x : g[t]) {
			q.push(x);
		}
		q.pop();
	}
}
int main() {
	cin >> n >> m;
	for (int i = 1; i <= m; i++) {
		int x, y;
		cin >> x >> y;
		g[x].push_back(y);
		g[y].push_back(x);
	}
	bfs(1);
	return 0;
}

AC:

结尾撒花,给点支持

  • 6
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值