C++无向图的邻接矩阵和DFS遍历的完整代码和输出数据
时间: 2024-05-13 14:16:28 浏览: 101
下面是C++实现无向图邻接矩阵和DFS遍历的完整代码和输出数据:
代码:
```c++
#include <iostream>
#include <vector>
#include <stack>
using namespace std;
const int MAXN = 100;
int n, e;
int mat[MAXN][MAXN];
bool vis[MAXN];
void dfs(int u) {
vis[u] = true;
cout << u << " ";
for (int i = 0; i < n; i++) {
if (mat[u][i] == 1 && !vis[i]) {
dfs(i);
}
}
}
int main() {
cout << "请输入图的顶点数和边数:";
cin >> n >> e;
cout << "请输入每条边所连接的两个顶点的编号:\n";
for (int i = 0; i < e; i++) {
int u, v;
cin >> u >> v;
mat[u][v] = mat[v][u] = 1; // 无向图
}
cout << "邻接矩阵表示的无向图:\n";
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
cout << mat[i][j] << " ";
}
cout << endl;
}
cout << "DFS遍历的结果:\n";
dfs(0);
cout << endl;
return 0;
}
```
输出:
```
请输入图的顶点数和边数:5 6
请输入每条边所连接的两个顶点的编号:
0 1
0 2
1 2
1 3
2 3
3 4
邻接矩阵表示的无向图:
0 1 1 0 0
1 0 1 1 0
1 1 0 1 0
0 1 1 0 1
0 0 0 1 0
DFS遍历的结果:
0 1 2 3 4
```
阅读全文
相关推荐















