用c语言实现无向图的创建和深度优先遍历
时间: 2024-06-13 21:06:48 浏览: 106
以下是C语言实现无向图的创建和深度优先遍历的示例代码:
```c
#include <stdio.h>
#include <stdlib.h>
#define MAX_VERTEX_NUM 20 // 最大顶点数
typedef struct {
int vertex[MAX_VERTEX_NUM]; // 顶点数组
int edge[MAX_VERTEX_NUM][MAX_VERTEX_NUM]; // 邻接矩阵
int vertex_num; // 顶点数
int edge_num; // 边数
} Graph;
int visited[MAX_VERTEX_NUM]; // 记录顶点是否被访问过
// 创建无向图
void createGraph(Graph *G) {
printf("请输入顶点数和边数:\n");
scanf("%d %d", &G->vertex_num, &G->edge_num);
printf("请输入顶点信息:\n");
for (int i = 0; i < G->vertex_num; i++) {
scanf("%d", &G->vertex[i]);
}
for (int i = 0; i < G->vertex_num; i++) {
for (int j = 0; j < G->vertex_num; j++) {
G->edge[i][j] = 0;
}
}
printf("请输入每条边的两个顶点:\n");
for (int k = 0; k < G->edge_num; k++) {
int i, j;
scanf("%d %d", &i, &j);
G->edge[i][j] = 1;
G->edge[j][i] = 1;
}
}
// 深度优先遍历
void DFS(Graph G, int v) {
visited[v] = 1;
printf("%d ", G.vertex[v]);
for (int i = 0; i < G.vertex_num; i++) {
if (G.edge[v][i] == 1 && visited[i] == 0) {
DFS(G, i);
}
}
}
int main() {
Graph G;
createGraph(&G);
printf("请输入起始顶点:\n");
int v;
scanf("%d", &v);
printf("深度优先遍历序列为:\n");
DFS(G, v);
printf("\n");
return 0;
}
```
阅读全文
相关推荐
![-](https://img-home.csdnimg.cn/images/20241231045021.png)
![-](https://img-home.csdnimg.cn/images/20241231045021.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)