C语言完整代码实现图的深度优先遍历以及广度优先遍历
时间: 2023-10-04 22:05:52 浏览: 125
图的深度优先遍历与广度优先遍历(C语言实现)
5星 · 资源好评率100%
以下是C语言完整代码实现图的深度优先遍历以及广度优先遍历的示例:
```c
#include <stdio.h>
#include <stdlib.h>
#define MAX_VERTICES 100
typedef struct Graph {
int num_vertices;
int adj_matrix[MAX_VERTICES][MAX_VERTICES];
} Graph;
typedef struct Queue {
int items[MAX_VERTICES];
int front;
int rear;
} Queue;
void init_graph(Graph* graph, int num_vertices) {
graph->num_vertices = num_vertices;
int i, j;
for (i = 0; i < num_vertices; i++) {
for (j = 0; j < num_vertices; j++) {
graph->adj_matrix[i][j] = 0;
}
}
}
void add_edge(Graph* graph, int src, int dest) {
graph->adj_matrix[src][dest] = 1;
graph->adj_matrix[dest][src] = 1;
}
void dfs(Graph* graph, int start_vertex, int visited[]) {
visited[start_vertex] = 1;
printf("%d ", start_vertex);
int i;
for (i = 0; i < graph->num_vertices; i++) {
if (graph->adj_matrix[start_vertex][i] == 1 && !visited[i]) {
dfs(graph, i, visited);
}
}
}
void bfs(Graph* graph, int start_vertex, int visited[]) {
Queue q;
q.front = -1;
q.rear = -1;
q.items[++q.rear] = start_vertex;
visited[start_vertex] = 1;
while (q.front != q.rear) {
int current_vertex = q.items[++q.front];
printf("%d ", current_vertex);
int i;
for (i = 0; i < graph->num_vertices; i++) {
if (graph->adj_matrix[current_vertex][i] == 1 && !visited[i]) {
q.items[++q.rear] = i;
visited[i] = 1;
}
}
}
}
int main() {
Graph graph;
init_graph(&graph, 6);
add_edge(&graph, 0, 1);
add_edge(&graph, 0, 2);
add_edge(&graph, 1, 3);
add_edge(&graph, 1, 4);
add_edge(&graph, 2, 4);
add_edge(&graph, 3, 5);
add_edge(&graph, 4, 5);
int visited[MAX_VERTICES] = {0};
printf("DFS: ");
dfs(&graph, 0, visited);
printf("\n");
for (int i = 0; i < graph.num_vertices; i++) {
visited[i] = 0;
}
printf("BFS: ");
bfs(&graph, 0, visited);
printf("\n");
return 0;
}
```
在此示例中,我们使用邻接矩阵来表示图,并实现了 `init_graph` 函数来初始化图。我们还实现了 `add_edge` 函数来添加边。
在 `dfs` 函数中,我们使用递归来深度优先遍历图,并在遍历每个节点时打印其值。在 `bfs` 函数中,我们使用队列来广度优先遍历图,并在遍历每个节点时打印其值。
最后,在 `main` 函数中,我们创建了一个具有6个节点的图,并使用 `dfs` 和 `bfs` 函数对其进行遍历。
阅读全文