c语言深度优先广度优先
时间: 2023-06-22 18:17:33 浏览: 128
深度优先搜索和广度优先搜索是两种常用的图搜索算法。在C语言中,实现深度优先搜索和广度优先搜索的方法如下:
深度优先搜索(DFS):
使用递归或栈来实现深度优先搜索。从起点开始,沿着一条路径一直走到终点,直到无法继续为止,然后返回上一级节点,继续走其他路径,直到找到终点。
广度优先搜索(BFS):
使用队列来实现广度优先搜索。从起点开始,将其入队,然后对队列中的每个节点,依次访问其相邻节点,并将其入队,直到找到终点。
以下是一个简单的深度优先搜索和广度优先搜索的示例代码:
```c
#include <stdio.h>
#include <stdlib.h>
#define MAX_SIZE 100
typedef struct Node {
int data;
struct Node* next;
} Node;
typedef struct Graph {
int num_vertices;
Node** adj_list;
int* visited;
} Graph;
Node* create_node(int data) {
Node* new_node = (Node*) malloc(sizeof(Node));
new_node->data = data;
new_node->next = NULL;
return new_node;
}
Graph* create_graph(int num_vertices) {
Graph* graph = (Graph*) malloc(sizeof(Graph));
graph->num_vertices = num_vertices;
graph->visited = (int*) malloc(num_vertices * sizeof(int));
graph->adj_list = (Node**) malloc(num_vertices * sizeof(Node*));
int i;
for (i = 0; i < num_vertices; i++) {
graph->visited[i] = 0;
graph->adj_list[i] = NULL;
}
return graph;
}
void add_edge(Graph* graph, int src, int dest) {
Node* new_node = create_node(dest);
new_node->next = graph->adj_list[src];
graph->adj_list[src] = new_node;
}
void dfs(Graph* graph, int vertex) {
graph->visited[vertex] = 1;
printf("%d ", vertex);
Node* adj_list = graph->adj_list[vertex];
while (adj_list != NULL) {
int connected_vertex = adj_list->data;
if (graph->visited[connected_vertex] == 0) {
dfs(graph, connected_vertex);
}
adj_list = adj_list->next;
}
}
void bfs(Graph* graph, int start_vertex) {
int queue[MAX_SIZE];
int front = -1;
int rear = -1;
queue[++rear] = start_vertex;
graph->visited[start_vertex] = 1;
while (front != rear) {
int vertex = queue[++front];
printf("%d ", vertex);
Node* adj_list = graph->adj_list[vertex];
while (adj_list != NULL) {
int connected_vertex = adj_list->data;
if (graph->visited[connected_vertex] == 0) {
graph->visited[connected_vertex] = 1;
queue[++rear] = connected_vertex;
}
adj_list = adj_list->next;
}
}
}
int main() {
Graph* graph = create_graph(4);
add_edge(graph, 0, 1);
add_edge(graph, 0, 2);
add_edge(graph, 1, 2);
add_edge(graph, 2, 0);
add_edge(graph, 2, 3);
add_edge(graph, 3, 3);
printf("DFS traversal: ");
dfs(graph, 2);
printf("\nBFS traversal: ");
bfs(graph, 2);
printf("\n");
return 0;
}
```
该代码使用邻接表表示图,并实现了深度优先搜索和广度优先搜索。在主函数中,创建图并添加边,然后调用dfs()和bfs()函数,分别进行深度优先搜索和广度优先搜索。
阅读全文