深度优先搜索的优先遍历深度更大的顶点,所以我们可以借助栈这一数据结构来实现:
1 将要访问的第一个顶点 v 入栈,然后首先对其进行访问;
2 将顶点 v 出栈,依次将与顶点 v 相邻且未被访问的顶点 c 压入栈中;
3 重复第一步操作,直至栈为空。
#include <iostream>
#include <vector>
#include <cstring>
using namespace std;
class Graph {
private:
int n; //!< 顶点数量
vector<int> *edges; //!< 邻接表
bool *visited;
public:
Graph(int input_n) {
n = input_n;
edges = new vector<int>[n];
visited=new bool[n];
memset(visited,0,n);
}
~Graph() {
delete[] edges;
delete[] visited;
}
void insert(int x, int y) {
edges[x].push_back(y);
edges[y].push_back(x);
}
void dfs(int vertex) {
cout<<vertex<<endl;
visited[vertex]=true;
for(int adj_vertex:edges[vertex]){
if( !visited[adj_vertex]){
dfs(adj_vertex);
}
}
}
};
int main() {
int n, m, k;
cin >> n >> m;
Graph g(n);
for (int i = 0; i < m; ++i) {
int x, y;
cin >> x >> y;
g.insert(x, y);
}
cin >> k;
g.dfs(k);
return 0;
}