图的dfs遍历题目描述一个有 n个结点的无向连通图这些结点以编号:123…n进行编号现给出结点间的连接关系。请以结点 1 为起点按dfs深度优先搜索、优先访问小编号结点的顺序遍历并输出该图。输入第一行为两整数n 和 e 表示 n 个顶点e 条边。 2≤ne≤10以下 e 行每行两个数表示两个结点是连通的。输出只有一行为按照优先访问小编号结点的dfs的结果。样例输入5 71 21 31 42 42
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
void dfs(vector<vector<int>>& graph, vector<bool>& visited, int node) {
visited[node] = true;
cout << node << " ";
for (int i = 0; i < graph[node].size(); i++) {
int neighbor = graph[node][i];
if (!visited[neighbor]) {
dfs(graph, visited, neighbor);
}
}
}
int main() {
int n, e;
cin >> n >> e;
vector<vector<int>> graph(n+1);
vector<bool> visited(n+1, false);
for (int i = 0; i < e; i++) {
int x, y;
cin >> x >> y;
graph[x].push_back(y);
graph[y].push_back(x);
}
for (int i = 1; i <= n; i++) {
sort(graph[i].begin(), graph[i].end());
}
dfs(graph, visited, 1);
return 0;
}
``
原文地址: https://www.cveoy.top/t/topic/hRXb 著作权归作者所有。请勿转载和采集!