给定无向图建立邻接矩阵和邻接表并遍历该图,以C语言实现
时间: 2025-01-05 10:45:58 浏览: 6
在C语言中,我们可以使用结构体和数组来创建邻接矩阵和邻接表,这两种数据结构常用于表示无向图。以下是简化的实现:
**邻接矩阵**:
```c
typedef struct {
int V; // 图中顶点数
int **adj; // 存储邻接矩阵的二维数组
} AdjMatrix;
void createAdjMatrix(AdjMatrix* graph, int vertices[], int edges[]) {
graph->V = vertices[0];
graph->adj = (int **)malloc(graph->V * sizeof(int *));
for (int i = 0; i < graph->V; i++) {
graph->adj[i] = (int *)malloc(graph->V * sizeof(int));
for (int j = 0; j < graph->V; j++)
graph->adj[i][j] = 0;
}
for (int i = 0; i < graph->V && edges[i] != -1; i += 2) {
int src = vertices[edges[i]], dest = vertices[edges[i + 1]];
graph->adj[src][dest] = 1;
graph->adj[dest][src] = 1; // 对称图,不需要额外赋值
}
}
// 遍历邻接矩阵
void traverseAdjMatrix(AdjMatrix* graph, int vertex) {
int* row = graph->adj[vertex];
for (int i = 0; i < graph->V; i++)
if (row[i])
printf("From %d to %d\n", vertex, i);
}
```
**邻接表**:
```c
typedef struct Node {
int dest;
struct Node* next;
} Edge;
typedef struct {
int V;
Edge** adjList; // 存储邻接表的链表数组
} AdjList;
void createAdjList(AdjList* graph, int vertices[], int edges[]) {
graph->V = vertices[0];
graph->adjList = (Edge **)malloc(graph->V * sizeof(Edge*));
for (int i = 0; i < graph->V; i++) {
graph->adjList[i] = NULL;
}
for (int i = 0; i < graph->V && edges[i] != -1; i += 2) {
int src = vertices[edges[i]], dest = vertices[edges[i + 1]];
Edge* edge = (Edge*)malloc(sizeof(Edge));
edge->dest = dest;
edge->next = graph->adjList[src];
graph->adjList[src] = edge;
}
}
// 遍历邻接表
void traverseAdjList(AdjList* graph, int vertex) {
Edge* current = graph->adjList[vertex];
while (current) {
printf("From %d to %d\n", vertex, current->dest);
current = current->next;
}
}
```
阅读全文