图的深度优先搜索和广度优先搜索 C++样例代码
时间: 2024-02-03 20:13:20 浏览: 68
深度优先搜索(DFS):
```c++
#include <bits/stdc++.h>
using namespace std;
const int MAXN = 1005;
vector<int> g[MAXN];
bool vis[MAXN];
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() {
int n, m;
cin >> n >> m;
for (int i = 1; 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 <bits/stdc++.h>
using namespace std;
const int MAXN = 1005;
vector<int> g[MAXN];
bool vis[MAXN];
void bfs(int u) {
queue<int> q;
q.push(u);
vis[u] = true;
while (!q.empty()) {
int cur = q.front();
q.pop();
cout << cur << " ";
for (int i = 0; i < g[cur].size(); i++) {
int v = g[cur][i];
if (!vis[v]) {
q.push(v);
vis[v] = true;
}
}
}
}
int main() {
int n, m;
cin >> n >> m;
for (int i = 1; i <= m; i++) {
int u, v;
cin >> u >> v;
g[u].push_back(v);
g[v].push_back(u);
}
bfs(1);
return 0;
}
```
阅读全文