用c语言,实现有向图的邻接矩阵存储结构。实现图的邻接表存储结构及一些基本操作功能,在此基础上实现并测试图的深度遍历算法。在此基础上图的广度优先遍历算法并进行测试
时间: 2024-12-29 11:28:40 浏览: 24
在C语言中,我们可以使用二维数组(邻接矩阵)或链表(邻接表)来实现有向图的数据结构。
**邻接矩阵存储结构**:
```c
typedef struct {
int size;
int **adjMatrix; // 用于表示图的邻接矩阵
} AdjacencyMatrixGraph;
AdjacencyMatrixGraph* createAdjMatrix(int vertices) {
AdjacencyMatrixGraph *graph = malloc(sizeof(AdjacencyMatrixGraph));
graph->size = vertices;
graph->adjMatrix = (int **)malloc(vertices * sizeof(int *));
for (int i = 0; i < vertices; i++) {
graph->adjMatrix[i] = (int *)malloc(vertices * sizeof(int));
for (int j = 0; j < vertices; j++) {
graph->adjMatrix[i][j] = 0; // 初始值设为无边
}
}
return graph;
}
// 添加边到矩阵
void addEdge(int matrixGraph[], int src, int dest) {
matrixGraph[src][dest] = 1; // 如果从src到dest有一条边,则置1
}
```
**邻接表存储结构**:
```c
typedef struct Node {
int data;
struct Node *next;
} Node;
typedef struct {
int size;
Node **adjList; // 邻接表头节点数组
} AdjacencyListGraph;
AdjacencyListGraph* createAdjList(int vertices) {
AdjacencyListGraph *graph = malloc(sizeof(AdjacencyListGraph));
graph->size = vertices;
graph->adjList = (Node **)malloc(vertices * sizeof(Node *));
for (int i = 0; i < vertices; i++) {
graph->adjList[i] = NULL;
}
return graph;
}
// 添加边到邻接列表
void addEdgeAdjList(Node **adjList, int src, int dest) {
Node *newNode = malloc(sizeof(Node));
newNode->data = dest;
newNode->next = adjList[src];
adjList[src] = newNode;
}
```
**深度优先遍历(DFS)**:
```c
void dfs(AdjacencyMatrixGraph *matrixGraph, int vertex, int visited[]) {
visited[vertex] = 1;
printf("%d ", vertex);
for (int i = 0; i < matrixGraph->size; i++) {
if (matrixGraph->adjMatrix[vertex][i] && !visited[i]) {
dfs(matrixGraph, i, visited);
}
}
}
```
**广度优先遍历(BFS)**:
```c
void bfs(AdjacencyListGraph *listGraph, int startVertex) {
int queue[vertices], front = -1, rear = -1;
bool visited[vertices] = {false};
queue[++rear] = startVertex;
visited[startVertex] = true;
while (front != rear) {
int curr = queue[++front];
printf("%d ", curr);
for (Node *node = listGraph->adjList[curr]; node; node = node->next) {
int neighbor = node->data;
if (!visited[neighbor]) {
queue[++rear] = neighbor;
visited[neighbor] = true;
}
}
}
}
```
你可以根据需要分别创建邻接矩阵和邻接表版本的图,并通过调用相应的遍历函数来测试它们。记得为每个节点分配唯一标识,并处理输入数据的有效性。完成上述代码后,可以创建若干顶点和边,然后对这些遍历算法进行测试。
阅读全文