图的深度优先遍历代码C语言
时间: 2024-06-13 07:09:45 浏览: 125
以下是图的深度优先遍历的C语言代码:
```c
#include <stdio.h>
#include <stdlib.h>
#define MAX_VERTEX_NUM 20
typedef struct ArcNode {
int adjvex;
struct ArcNode *next;
} ArcNode;
typedef struct VNode {
int data;
ArcNode *firstarc;
} VNode, AdjList[MAX_VERTEX_NUM];
typedef struct {
AdjList vertices;
int vexnum, arcnum;
} ALGraph;
void DFS(ALGraph *G, int v, int *visited) {
visited[v] = 1;
printf("%d ", G->vertices[v].data);
ArcNode *p = G->vertices[v].firstarc;
while (p != NULL) {
if (!visited[p->adjvex]) {
DFS(G, p->adjvex, visited);
}
p = p->next;
}
}
void DFSTraverse(ALGraph *G) {
int visited[MAX_VERTEX_NUM] = {0};
for (int i = 0; i < G->vexnum; i++) {
if (!visited[i]) {
DFS(G, i, visited);
}
}
}
int main() {
ALGraph G;
G.vexnum = 5;
G.arcnum = 5;
for (int i = 0; i < G.vexnum; i++) {
G.vertices[i].data = i + 1;
G.vertices[i].firstarc = NULL;
}
int edges[5][2] = {{0, 1}, {0, 2}, {1, 3}, {2, 3}, {3, 4}};
for (int i = 0; i < G.arcnum; i++) {
int v1 = edges[i][0];
int v2 = edges[i][1];
ArcNode *p = (ArcNode *)malloc(sizeof(ArcNode));
p->adjvex = v2;
p->next = G.vertices[v1].firstarc;
G.vertices[v1].firstarc = p;
p = (ArcNode *)malloc(sizeof(ArcNode));
p->adjvex = v1;
p->next = G.vertices[v2].firstarc;
G.vertices[v2].firstarc = p;
}
printf("DFS: ");
DFSTraverse(&G);
return 0;
}
```
阅读全文