用c语言创建一个无向图,选用邻接表法数据存储结构,并求出任意一个顶的度。同时写出图的深度,广度遍历算法,以及注释出每一个步骤的作用
时间: 2023-12-04 10:05:23 浏览: 39
好的,我可以为您解答这个问题。
首先,让我们了解一下邻接表法的数据存储结构。邻接表法是一种常见的图的表示方法,它将图中每个顶点的所有相邻顶点存储在一个链表中,所有链表组成一个数组。这种表示方法可以有效地节省空间,并且能够方便地找到每个顶点的相邻顶点。
下面是用C语言创建一个无向图,并选用邻接表法数据存储结构的代码:
```c
#include<stdio.h>
#include<stdlib.h>
// 定义邻接表节点
typedef struct node {
int vertex; // 顶点
struct node* next; // 指向下一个节点的指针
} Node;
// 定义邻接表
typedef struct graph {
int numVertices; // 图中顶点的数量
Node** adjLists; // 存储顶点的链表数组
} Graph;
// 创建节点
Node* createNode(int v) {
Node* node = (Node*)malloc(sizeof(Node));
node->vertex = v;
node->next = NULL;
return node;
}
// 创建图
Graph* createGraph(int vertices) {
Graph* graph = (Graph*)malloc(sizeof(Graph));
graph->numVertices = vertices;
graph->adjLists = (Node**)malloc(vertices * sizeof(Node*));
int i;
for (i = 0; i < vertices; i++)
graph->adjLists[i] = NULL;
return graph;
}
// 添加边
void addEdge(Graph* graph, int src, int dest) {
// 添加从源到目标的边
Node* node = createNode(dest);
node->next = graph->adjLists[src];
graph->adjLists[src] = node;
// 添加从目标到源的边
node = createNode(src);
node->next = graph->adjLists[dest];
graph->adjLists[dest] = node;
}
// 求顶的度
int findDegree(Graph* graph, int vertex) {
int degree = 0;
Node* temp = graph->adjLists[vertex];
while (temp) {
degree++;
temp = temp->next;
}
return degree;
}
// 深度优先遍历
void DFS(Graph* graph, int vertex, int* visited) {
visited[vertex] = 1;
printf("%d ", vertex);
Node* temp = graph->adjLists[vertex];
while (temp) {
int adjVertex = temp->vertex;
if (visited[adjVertex] == 0)
DFS(graph, adjVertex, visited);
temp = temp->next;
}
}
// 广度优先遍历
void BFS(Graph* graph, int startVertex, int* visited) {
int queue[graph->numVertices];
int front = 0, rear = 0;
visited[startVertex] = 1;
queue[rear] = startVertex;
rear++;
while (front < rear) {
int currVertex = queue[front];
printf("%d ", currVertex);
front++;
Node* temp = graph->adjLists[currVertex];
while (temp) {
int adjVertex = temp->vertex;
if (visited[adjVertex] == 0) {
visited[adjVertex] = 1;
queue[rear] = adjVertex;
rear++;
}
temp = temp->next;
}
}
}
// 主函数
int main() {
Graph* graph = createGraph(4);
addEdge(graph, 0, 1);
addEdge(graph, 0, 2);
addEdge(graph, 1, 2);
addEdge(graph, 2, 3);
printf("Vertex 2's degree: %d\n", findDegree(graph, 2));
int visited[4] = {0};
printf("Depth First Search: ");
DFS(graph, 0, visited);
printf("\n");
visited[4] = {0};
printf("Breadth First Search: ");
BFS(graph, 0, visited);
return 0;
}
```
这个代码创建了一个包含4个顶点的无向图,然后添加了4条边。然后使用 `findDegree` 函数求出顶点2的度,并使用 `DFS` 函数和 `BFS` 函数分别进行深度优先遍历和广度优先遍历。
在这个代码中,每个节点都是一个结构体,其中包含一个顶点和一个指向下一个节点的指针。 `createNode` 函数创建一个新节点, `addEdge` 函数添加两条边,一条从源到目标,一条从目标到源。
`createGraph` 函数创建一个新的图,并分配一个指向链表数组的指针。 `findDegree` 函数遍历链表,计算顶点的度数。
`DFS` 函数使用递归方式进行深度优先遍历。它使用一个 `visited` 数组来跟踪哪些顶点已经被访问过。 `BFS` 函数使用队列进行广度优先遍历。它使用一个 `visited` 数组来跟踪哪些顶点已经被访问过。