2350: 【入门】图的bfs遍历(2053)

内存限制:128 MB 时间限制:1.000 S
评测方式:文本比较 命题人:
提交:4 解决:3

题目描述

一个有 lns="http://www.w3.org/1998/Math/MathML"> 个结点的无向连通图,这些结点以编号:lns="http://www.w3.org/1998/Math/MathML">1,2 进行编号,现给出结点间的连接关系。

请以结点 lns="http://www.w3.org/1998/Math/MathML">1 为起点,按广度优先搜索(bfs)、优先访问小编号结点的顺序遍历并输出该图。

输入

第一行为两整数,lns="http://www.w3.org/1998/Math/MathML"> 和 lns="http://www.w3.org/1998/Math/MathML"> ,表示 lns="http://www.w3.org/1998/Math/MathML"> 个顶点,lns="http://www.w3.org/1998/Math/MathML"> 条边。( lns="http://www.w3.org/1998/Math/MathML">2,10 )

以下 lns="http://www.w3.org/1998/Math/MathML"> 行每行两个数,表示两个结点是连通的。

输出

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

样例输入 复制

5 7
1 2
1 3
1 4
2 4
2 5
3 5
4 5

样例输出 复制

1 2 3 4 5

提示



#include<bits/stdc++.h>
using namespace std;
#define MAXN 20
int n,e;
vector <int> p[MAXN];
bool u[MAXN];
queue <int> q;
void bfs() {
	u[1] = true;
	q.push(1);
	while (!q.empty()) {
		int x = q.front();
		cout << x << " ";
		q.pop();
		for (int i = 0, sz = p[x].size(); i < sz ; i++) {
			if (!u[p[x][i]]) {
				u[p[x][i]] = true;
				q.push(p[x][i]);
			}
		}
	}
}
int main(){
    cin >> n >> e;
    for (int i = 1; i <=e ; i++) {
    	int u,v;
    	cin >> u >> v;
    	p.push_back(v);
	}
	bfs();
	return 0;
}