实现图的存储,输出存储结构示意图 输出对建立的图进行深度优先搜索和广度优先搜索所得的遍历序列。C语言代码实现
时间: 2024-04-30 14:19:13 浏览: 104
图的存储可以采用邻接矩阵或邻接表两种方式,这里以邻接表为例。
邻接表的数据结构包含两个部分:一个顶点数组和一个边表数组。顶点数组中存储了图中所有顶点信息,每个顶点信息包括顶点名称和该顶点在边表数组中对应的位置。边表数组中存储了所有边的信息,每个节点包括邻接点的位置和权值。
存储结构示意图如下:
```
0
/ \
1 - 2
/ \ / \
3 - 4 - 5
```
顶点数组:
```
Vertex Array:
-------------
| 0 | 1 | 2 | 3 | 4 | 5 |
-------------
```
边表数组:
```
Edge Array:
-------------
| 1 -> 2 | 1 -> 4 |
| 2 -> 0 | 2 -> 1 | 2 -> 4 | 2 -> 5 |
| 3 -> 1 | 3 -> 4 |
| 4 -> 1 | 4 -> 2 | 4 -> 3 | 4 -> 5 |
| 5 -> 2 | 5 -> 4 |
-------------
```
深度优先搜索(DFS)的过程是从起始顶点开始,沿着一条路径访问图中的顶点,直到不能继续为止,然后返回到前一个顶点,继续沿着另一条路径进行访问。具体实现可以采用递归或栈的方式。
下面是C语言代码实现:
```c
#include <stdio.h>
#include <stdlib.h>
#define MAX_VERTICES 10
// 邻接表中的边结构体
typedef struct Edge {
int dest; // 邻接点位置
int weight; // 权值
struct Edge* next; // 指向下一条边
} Edge;
// 邻接表中的顶点结构体
typedef struct Vertex {
int name; // 顶点名称
Edge* head; // 指向第一条边
} Vertex;
// 邻接表结构体
typedef struct Graph {
Vertex vertices[MAX_VERTICES]; // 存储所有顶点
int num_vertices; // 顶点个数
} Graph;
// 初始化图
void initGraph(Graph* graph, int n) {
graph->num_vertices = n;
for (int i = 0; i < n; i++) {
graph->vertices[i].name = i;
graph->vertices[i].head = NULL;
}
}
// 添加边
void addEdge(Graph* graph, int src, int dest, int weight) {
Edge* edge = (Edge*) malloc(sizeof(Edge));
edge->dest = dest;
edge->weight = weight;
edge->next = graph->vertices[src].head;
graph->vertices[src].head = edge;
}
// 深度优先搜索
void DFS(Graph* graph, int v, int* visited) {
printf("%d ", v);
visited[v] = 1;
Edge* edge = graph->vertices[v].head;
while (edge != NULL) {
int w = edge->dest;
if (!visited[w]) {
DFS(graph, w, visited);
}
edge = edge->next;
}
}
// 广度优先搜索
void BFS(Graph* graph, int v, int* visited) {
int queue[MAX_VERTICES];
int front = 0;
int rear = 0;
queue[rear++] = v;
visited[v] = 1;
while (front != rear) {
int w = queue[front++];
printf("%d ", w);
Edge* edge = graph->vertices[w].head;
while (edge != NULL) {
int u = edge->dest;
if (!visited[u]) {
visited[u] = 1;
queue[rear++] = u;
}
edge = edge->next;
}
}
}
// 主函数
int main() {
Graph graph;
initGraph(&graph, 6);
addEdge(&graph, 0, 1, 0);
addEdge(&graph, 0, 2, 0);
addEdge(&graph, 1, 0, 0);
addEdge(&graph, 1, 2, 0);
addEdge(&graph, 1, 3, 0);
addEdge(&graph, 2, 0, 0);
addEdge(&graph, 2, 1, 0);
addEdge(&graph, 2, 4, 0);
addEdge(&graph, 2, 5, 0);
addEdge(&graph, 3, 1, 0);
addEdge(&graph, 3, 4, 0);
addEdge(&graph, 4, 2, 0);
addEdge(&graph, 4, 3, 0);
addEdge(&graph, 4, 5, 0);
addEdge(&graph, 5, 2, 0);
addEdge(&graph, 5, 4, 0);
int visited[MAX_VERTICES] = {0};
printf("DFS: ");
DFS(&graph, 0, visited);
printf("\nBFS: ");
for (int i = 0; i < graph.num_vertices; i++) {
visited[i] = 0;
}
BFS(&graph, 0, visited);
printf("\n");
return 0;
}
```
阅读全文