dfs和bfs算法实现c++
时间: 2023-08-29 07:07:28 浏览: 95
DFS算法实现:
```c++
#include <iostream>
#include <vector>
#include <stack>
using namespace std;
void dfs(vector<vector<int>>& graph, int start) {
vector<bool> visited(graph.size(), false);
stack<int> s;
s.push(start);
while (!s.empty()) {
int cur = s.top();
s.pop();
if (!visited[cur]) {
visited[cur] = true;
cout << cur << " ";
for (int i = graph[cur].size() - 1; i >= 0; i--) {
int neighbor = graph[cur][i];
if (!visited[neighbor]) {
s.push(neighbor);
}
}
}
}
}
int main() {
vector<vector<int>> graph = {
{1, 2},
{0, 2, 3},
{0, 1, 3},
{1, 2}
};
dfs(graph, 0);
return 0;
}
```
BFS算法实现:
```c++
#include <iostream>
#include <vector>
#include <queue>
using namespace std;
void bfs(vector<vector<int>>& graph, int start) {
vector<bool> visited(graph.size(), false);
queue<int> q;
q.push(start);
while (!q.empty()) {
int cur = q.front();
q.pop();
if (!visited[cur]) {
visited[cur] = true;
cout << cur << " ";
for (int neighbor : graph[cur]) {
if (!visited[neighbor]) {
q.push(neighbor);
}
}
}
}
}
int main() {
vector<vector<int>> graph = {
{1, 2},
{0, 2, 3},
{0, 1, 3},
{1, 2}
};
bfs(graph, 0);
return 0;
}
```
阅读全文