【题目来源】
https://oj.czos.cn/p/2052
【题目描述】
一个有 n 个结点的无向连通图,这些结点以编号 1,2,...,n 进行编号,现给出结点间的连接关系。
请以结点 1 为起点,按 dfs(深度优先搜索)、优先访问小编号结点的顺序遍历并输出该图。
【输入格式】
第一行为两整数,n 和 e,表示 n 个顶点,e 条边。(2≤n,e≤10)
以下 e 行每行两个数,表示两个结点是连通的。
【输出格式】
只有一行,为按照优先访问小编号结点的 dfs 的结果。
【输入样例】
5 7
1 2
1 3
1 4
2 4
2 5
3 5
4 5
【输出样例】
1 2 4 5 3
【数据范围】
2≤n,e≤10
【算法分析】
链式前向星采用头插法构建,原生无法保证邻接点有序。
若要求按编号从小到大访问邻接点,有两种实现方式:一是使用邻接矩阵,二是先用 vector 邻接表存储,排序后再遍历。
【算法代码:邻接矩阵】
cpp
#include<bits/stdc++.h>
using namespace std;
const int N=1e3+5;
int g[N][N];
bool st[N];
int n,m;
void dfs(int u) {
st[u]=true;
cout<<u<<" ";
for(int j=1; j<=n; j++) {
if(g[u][j] && !st[j]) {
dfs(j);
}
}
}
int main() {
cin>>n>>m;
while(m--) {
int x,y;
cin>>x>>y;
g[x][y]=1;
g[y][x]=1;
}
dfs(1);
return 0;
}
/*
in:
5 7
1 2
1 3
1 4
2 4
2 5
3 5
4 5
out:
1 2 4 5 3
*/
【算法代码:邻接表】
cpp
#include <bits/stdc++.h>
using namespace std;
const int N=15;
vector<int> g[N];
bool st[N];
int n,m;
void dfs(int u,int fa) {
cout<<u<<" ";
st[u]=true;
for(int i=0; i<g[u].size(); i++) {
int t=g[u][i];
if(!st[t]) dfs(t,u);
}
}
int main() {
cin>>n>>m;
while(m--) {
int x,y;
cin>>x>>y;
g[x].push_back(y);
g[y].push_back(x);
}
for(int i=1; i<=n; i++) {
sort(g[i].begin(),g[i].end());
}
dfs(1,-1);
return 0;
}
/*
in:
5 7
1 2
1 3
1 4
2 4
2 5
3 5
4 5
out:
1 2 4 5 3
*/
【参考文献】
https://blog.csdn.net/hnjzsyjyj/article/details/139369904
https://blog.csdn.net/hnjzsyjyj/article/details/163437811
https://blog.csdn.net/hnjzsyjyj/article/details/139681246