c++实现dfs和bfs
时间: 2023-08-29 21:07:29 浏览: 106
以下是C++实现DFS和BFS的代码示例:
DFS(深度优先搜索):
```c++
#include <iostream>
#include <vector>
#include <stack>
using namespace std;
const int N = 1e5 + 10;
int n, m;
vector<int> g[N];
bool vis[N];
void dfs(int u) {
vis[u] = true;
cout << u << " ";
for (int i = 0; i < g[u].size(); i++) {
int v = g[u][i];
if (!vis[v]) {
dfs(v);
}
}
}
int main() {
cin >> n >> m;
for (int i = 0; i < m; i++) {
int u, v;
cin >> u >> v;
g[u].push_back(v);
g[v].push_back(u);
}
dfs(1);
return 0;
}
```
BFS(广度优先搜索):
```c++
#include <iostream>
#include <vector>
#include <queue>
using namespace std;
const int N = 1e5 + 10;
int n, m;
vector<int> g[N];
bool vis[N];
void bfs(int u) {
queue<int> q;
q.push(u);
vis[u] = true;
while (!q.empty()) {
int u = q.front();
q.pop();
cout << u << " ";
for (int i = 0; i < g[u].size(); i++) {
int v = g[u][i];
if (!vis[v]) {
vis[v] = true;
q.push(v);
}
}
}
}
int main() {
cin >> n >> m;
for (int i = 0; i < m; i++) {
int u, v;
cin >> u >> v;
g[u].push_back(v);
g[v].push_back(u);
}
bfs(1);
return 0;
}
```
阅读全文