用c++实现DFS算法
时间: 2023-08-04 17:15:38 浏览: 100
好的,以下是使用C++实现DFS算法的示例代码:
```c++
#include <iostream>
#include <vector>
#include <stack>
using namespace std;
void dfs(int node, vector<bool>& visited, vector<vector<int>>& graph) {
visited[node] = true;
cout << node << " ";
for (int i = 0; i < graph[node].size(); i++) {
int neighbor = graph[node][i];
if (!visited[neighbor]) {
dfs(neighbor, visited, graph);
}
}
}
void dfs_iterative(int start, vector<bool>& visited, vector<vector<int>>& graph) {
stack<int> s;
s.push(start);
while (!s.empty()) {
int node = s.top();
s.pop();
if (!visited[node]) {
visited[node] = true;
cout << node << " ";
for (int i = graph[node].size() - 1; i >= 0; i--) {
int neighbor = graph[node][i];
if (!visited[neighbor]) {
s.push(neighbor);
}
}
}
}
}
int main() {
int n = 5;
vector<vector<int>> graph(n);
// Add edges to the graph
graph[0].push_back(1);
graph[0].push_back(2);
graph[1].push_back(2);
graph[2].push_back(0);
graph[2].push_back(3);
graph[3].push_back(3);
// Initialize visited array
vector<bool> visited(n, false);
// Perform DFS
cout << "Recursive DFS: ";
dfs(2, visited, graph);
// Reset visited array
fill(visited.begin(), visited.end(), false);
cout << endl << "Iterative DFS: ";
dfs_iterative(2, visited, graph);
return 0;
}
```
此示例代码实现了两个函数:`dfs` 和 `dfs_iterative`。`dfs` 函数使用递归调用来实现深度优先搜索,而 `dfs_iterative` 函数使用栈来实现深度优先搜索。
示例代码中采用邻接表的方式来表示图。在这个例子中,我们从节点 2 开始遍历,输出了深度优先搜索的结果。
希望这个例子能够帮助您更好地理解如何使用C++实现DFS算法。
阅读全文