用c语言编写一个拥有菜单的系统,功能包括: (1)定义图的邻接表 (2)深度优先遍历 (3)广度优先遍历
时间: 2024-01-08 13:01:52 浏览: 70
好的,以下是一个简单的用C语言编写的图的邻接表、深度优先遍历和广度优先遍历的系统:
```c
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#define MAX_SIZE 10
// 邻接表表示法
typedef struct EdgeNode {
int adjvex; // 邻接点的下标
struct EdgeNode *next; // 指向下一个邻接点的指针
} EdgeNode;
typedef struct VertexNode {
int vertex; // 顶点信息
EdgeNode *first_edge; // 指向第一个邻接点的指针
} VertexNode;
typedef struct Graph {
VertexNode vertex[MAX_SIZE]; // 存放顶点信息和邻接表头指针
int vertex_num; // 顶点数
int edge_num; // 边数
} Graph;
// 初始化图
void initGraph(Graph *g) {
printf("请输入顶点数:");
scanf("%d", &g->vertex_num);
printf("请输入边数:");
scanf("%d", &g->edge_num);
printf("请输入顶点的值:\n");
for (int i = 0; i < g->vertex_num; i++) {
scanf("%d", &g->vertex[i].vertex);
g->vertex[i].first_edge = NULL;
}
printf("请输入边的信息(格式:a, b):\n");
for (int i = 0; i < g->edge_num; i++) {
int a, b;
scanf("%d, %d", &a, &b);
EdgeNode *node1 = (EdgeNode *)malloc(sizeof(EdgeNode));
node1->adjvex = b;
node1->next = g->vertex[a].first_edge;
g->vertex[a].first_edge = node1;
EdgeNode *node2 = (EdgeNode *)malloc(sizeof(EdgeNode));
node2->adjvex = a;
node2->next = g->vertex[b].first_edge;
g->vertex[b].first_edge = node2; // 无向图
}
}
// 深度优先遍历
void dfs(Graph g, int v, bool visited[]) {
visited[v] = true;
printf("%d ", g.vertex[v].vertex);
EdgeNode *p = g.vertex[v].first_edge;
while (p) {
if (!visited[p->adjvex]) {
dfs(g, p->adjvex, visited);
}
p = p->next;
}
}
void depthFirstSearch(Graph g) {
bool visited[MAX_SIZE] = {false};
printf("深度优先遍历的结果为:");
for (int i = 0; i < g.vertex_num; i++) {
if (!visited[i]) {
dfs(g, i, visited);
}
}
printf("\n");
}
// 广度优先遍历
void breadthFirstSearch(Graph g, int v, bool visited[]) {
int queue[MAX_SIZE];
int front = 0, rear = 0;
queue[rear++] = v;
visited[v] = true;
while (front < rear) {
int cur = queue[front++];
printf("%d ", g.vertex[cur].vertex);
EdgeNode *p = g.vertex[cur].first_edge;
while (p) {
if (!visited[p->adjvex]) {
queue[rear++] = p->adjvex;
visited[p->adjvex] = true;
}
p = p->next;
}
}
}
void breadthFirstSearch(Graph g) {
bool visited[MAX_SIZE] = {false};
printf("广度优先遍历的结果为:");
for (int i = 0; i < g.vertex_num; i++) {
if (!visited[i]) {
breadthFirstSearch(g, i, visited);
}
}
printf("\n");
}
int main() {
Graph g;
initGraph(&g);
depthFirstSearch(g);
breadthFirstSearch(g);
return 0;
}
```
这个系统可以让用户输入图的顶点数和边数,然后让用户输入每个顶点的值和每条边的信息。接着,它会使用邻接表表示法来存储图,并实现深度优先遍历和广度优先遍历。
阅读全文