用c语言实现,建立一个有向图的邻接表存储,然后逐个链表输出,然后从 0号顶点出发对该图进行广度优先搜索,按顺序输出所访问的顶点
时间: 2024-01-09 09:05:28 浏览: 176
好的,我可以为您解答这个问题。
首先,我们需要定义一个图的结构体。这个结构体包含一个顶点数目的变量和一个指向链表的指针数组。每个链表的节点包含一个指向邻接点的指针和一个权值。
```c
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#define MAX_VERTICES 100
// 邻接点结构体
typedef struct _Node {
int vertex; // 邻接点
int weight; // 权值
struct _Node *next; // 指向下一个邻接点的指针
} Node;
// 图的结构体
typedef struct _Graph {
int num_vertices; // 顶点数目
Node *adj_list[MAX_VERTICES]; // 指向链表的指针数组
} Graph;
```
接下来,我们需要实现一个函数来创建图。该函数接受一个顶点数目和一个邻接矩阵,然后返回一个指向图的指针。
```c
Graph *create_graph(int num_vertices, int **adj_matrix) {
Graph *graph = (Graph *)malloc(sizeof(Graph));
graph->num_vertices = num_vertices;
for (int i = 0; i < num_vertices; i++) {
graph->adj_list[i] = NULL;
for (int j = 0; j < num_vertices; j++) {
if (adj_matrix[i][j] != 0) {
Node *node = (Node *)malloc(sizeof(Node));
node->vertex = j;
node->weight = adj_matrix[i][j];
node->next = graph->adj_list[i];
graph->adj_list[i] = node;
}
}
}
return graph;
}
```
然后,我们需要实现一个函数来打印图。该函数遍历链表并逐个输出节点。
```c
void print_graph(Graph *graph) {
printf("Adjacency List:\n");
for (int i = 0; i < graph->num_vertices; i++) {
printf("%d: ", i);
Node *node = graph->adj_list[i];
while (node != NULL) {
printf("%d(%d) ", node->vertex, node->weight);
node = node->next;
}
printf("\n");
}
}
```
接下来,我们需要实现一个函数来进行广度优先搜索。该函数接受一个图和一个起始顶点,然后按照广度优先的顺序访问所有顶点并输出。
```c
void bfs(Graph *graph, int start_vertex) {
bool visited[MAX_VERTICES] = {false};
int queue[MAX_VERTICES];
int front = 0, rear = 0;
visited[start_vertex] = true;
queue[rear++] = start_vertex;
printf("BFS Order: ");
while (front != rear) {
int vertex = queue[front++];
printf("%d ", vertex);
Node *node = graph->adj_list[vertex];
while (node != NULL) {
int adj_vertex = node->vertex;
if (!visited[adj_vertex]) {
visited[adj_vertex] = true;
queue[rear++] = adj_vertex;
}
node = node->next;
}
}
printf("\n");
}
```
最后,我们需要在主函数中调用这些函数来创建图、打印图、进行广度优先搜索。
```c
int main() {
int num_vertices = 5;
int adj_matrix[5][5] = {
{0, 1, 1, 0, 0},
{1, 0, 0, 1, 1},
{1, 0, 0, 1, 0},
{0, 1, 1, 0, 1},
{0, 1, 0, 1, 0}
};
Graph *graph = create_graph(num_vertices, adj_matrix);
print_graph(graph);
bfs(graph, 0);
return 0;
}
```
这个程序将输出以下结果:
```
Adjacency List:
0: 1(1) 2(1)
1: 0(1) 3(1) 4(1)
2: 0(1) 3(1)
3: 1(1) 2(1) 4(1)
4: 1(1) 3(1)
BFS Order: 0 1 2 3 4
```
这个程序使用邻接表来存储图,并按照广度优先的顺序访问所有顶点。
阅读全文