2349: 【入门】图的dfs遍历(2052)

内存限制: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 为起点,按dfs(深度优先搜索)、优先访问小编号结点的顺序遍历并输出该图。

输入

第一行为两整数,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"> 行每行两个数,表示两个结点是连通的。

输出

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

样例输入 复制

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

样例输出 复制

1 2 4 5 3

提示



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