您的位置:首页 > 理论基础 > 数据结构算法

深度优先搜索

2016-05-31 23:13 260 查看
深度优先搜索的优先遍历深度更大的顶点,所以我们可以借助栈这一数据结构来实现:

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>
;
visited=new bool
;
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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  数据结构 遍历 搜索