(1)输入无向图的顶点数、边数及各条边的顶点对,建立用邻接表表示的无向图。 (2)对图进行深度优先搜索和广度优先搜索遍历,并分别输出其遍历序列。用C语言
时间: 2024-01-21 07:16:06 浏览: 68
C语言 输入无向图连通图的顶点数、顶点信息、边数、顶点对序列及遍历的起始点序号,输出深度优先遍历序列
5星 · 资源好评率100%
以下是C语言代码实现:
```c
#include <stdio.h>
#include <stdlib.h>
// 邻接表节点
typedef struct AdjListNode {
int dest;
struct AdjListNode* next;
} AdjListNode;
// 邻接表
typedef struct AdjList {
AdjListNode* head;
} AdjList;
// 图
typedef struct Graph {
int V; // 顶点数
AdjList* array;
} Graph;
// 创建邻接表节点
AdjListNode* newAdjListNode(int dest) {
AdjListNode* newNode = (AdjListNode*) malloc(sizeof(AdjListNode));
newNode->dest = dest;
newNode->next = NULL;
return newNode;
}
// 创建图
Graph* createGraph(int V) {
Graph* graph = (Graph*) malloc(sizeof(Graph));
graph->V = V;
// 创建邻接表数组
graph->array = (AdjList*) malloc(V * sizeof(AdjList));
// 初始化邻接表头节点为NULL
for (int i = 0; i < V; ++i) {
graph->array[i].head = NULL;
}
return graph;
}
// 添加边
void addEdge(Graph* graph, int src, int dest) {
// 添加src到dest的边
AdjListNode* newNode = newAdjListNode(dest);
newNode->next = graph->array[src].head;
graph->array[src].head = newNode;
// 添加dest到src的边
newNode = newAdjListNode(src);
newNode->next = graph->array[dest].head;
graph->array[dest].head = newNode;
}
// 深度优先搜索遍历
void DFSUtil(Graph* graph, int v, int visited[]) {
visited[v] = 1; // 标记为已访问
printf("%d ", v);
AdjListNode* node = graph->array[v].head;
while (node != NULL) {
int adjV = node->dest;
if (!visited[adjV]) {
DFSUtil(graph, adjV, visited);
}
node = node->next;
}
}
void DFS(Graph* graph) {
// 初始化所有顶点都未访问
int* visited = (int*) malloc(graph->V * sizeof(int));
for (int i = 0; i < graph->V; ++i) {
visited[i] = 0;
}
// 从每个未访问的顶点开始遍历
for (int i = 0; i < graph->V; ++i) {
if (!visited[i]) {
DFSUtil(graph, i, visited);
}
}
free(visited);
}
// 广度优先搜索遍历
void BFS(Graph* graph, int start) {
// 初始化所有顶点都未访问
int* visited = (int*) malloc(graph->V * sizeof(int));
for (int i = 0; i < graph->V; ++i) {
visited[i] = 0;
}
// 创建队列
int* queue = (int*) malloc(graph->V * sizeof(int));
int front = 0;
int rear = 0;
// 标记起始顶点为已访问并入队
visited[start] = 1;
queue[rear++] = start;
// 遍历队列直到为空
while (front != rear) {
// 出队并访问
int v = queue[front++];
printf("%d ", v);
// 将所有未访问的相邻顶点入队并标记为已访问
AdjListNode* node = graph->array[v].head;
while (node != NULL) {
int adjV = node->dest;
if (!visited[adjV]) {
visited[adjV] = 1;
queue[rear++] = adjV;
}
node = node->next;
}
}
free(visited);
free(queue);
}
int main() {
int V, E;
printf("请输入顶点数和边数:");
scanf("%d %d", &V, &E);
Graph* graph = createGraph(V);
// 添加边
for (int i = 0; i < E; ++i) {
int src, dest;
printf("请输入第%d条边的顶点对:", i+1);
scanf("%d %d", &src, &dest);
addEdge(graph, src, dest);
}
// 深度优先搜索遍历
printf("深度优先搜索遍历结果:");
DFS(graph);
printf("\n");
// 广度优先搜索遍历
printf("广度优先搜索遍历结果:");
BFS(graph, 0);
printf("\n");
return 0;
}
```
运行代码,输入顶点数、边数和各条边的顶点对,即可输出深度优先搜索和广度优先搜索遍历的结果。
阅读全文