c++实现图的深度优先遍历和广度优先遍历代码
时间: 2023-12-05 08:40:13 浏览: 140
以下是C++实现图的深度优先遍历和广度优先遍历的代码:
深度优先遍历:
```c++
#include<iostream>
#include<cstring>
#include<queue>
using namespace std;
const int N = 100010;
int h[N], e[N], ne[N], idx;
bool st[N];
void add(int a, int b)
{
e[idx] = b, ne[idx] = h[a], h[a] = idx ++ ;
}
void dfs(int u)
{
st[u] = true;
cout << u << " ";
for (int i = h[u]; ~i; i = ne[i])
{
int j = e[i];
if (!st[j]) dfs(j);
}
}
int main()
{
memset(h, -1, sizeof h);
int n, m, u, v;
cin >> n >> m >> u;
while (m -- )
{
cin >> u >> v;
add(u, v);
add(v, u);
}
dfs(u);
return 0;
}
```
广度优先遍历:
```c++
#include<iostream>
#include<cstring>
#include<queue>
using namespace std;
const int N = 100010;
int h[N], e[N], ne[N], idx;
bool st[N];
void add(int a, int b)
{
e[idx] = b, ne[idx] = h[a], h[a] = idx ++ ;
}
void bfs(int u)
{
queue<int> q;
q.push(u);
st[u] = true;
while (q.size())
{
int t = q.front();
q.pop();
cout << t << " ";
for (int i = h[t]; ~i; i = ne[i])
{
int j = e[i];
if (!st[j])
{
q.push(j);
st[j] = true;
}
}
}
}
int main()
{
memset(h, -1, sizeof h);
int n, m, u, v;
cin >> n >> m >> u;
while (m -- )
{
cin >> u >> v;
add(u, v);
add(v, u);
}
bfs(u);
return 0;
}
```
阅读全文