1、实现图的存储:邻接矩阵或邻接表。 2、基本操作: 1)判断是否是无向图。 2)求图中顶点的度。 3)实现图的遍历 根据图中的内容,按以上要求给出一个完整的C语言代码
时间: 2025-01-26 09:10:32 浏览: 23
在C语言中,我们通常使用结构体来表示图,并结合邻接矩阵或邻接表这两种数据结构来存储图。这里是一个简单的例子:
1. **邻接矩阵**:
```c
typedef struct {
int vertices; // 顶点数
int* adjMatrix; // 邻接矩阵数组,大小为vertices * vertices
} GraphAdjMat;
// 初始化邻接矩阵
void initAdjMat(GraphAdjMat* graph, int vertices) {
graph->vertices = vertices;
graph->adjMatrix = malloc(sizeof(int) * vertices * vertices);
for (int i = 0; i < vertices; i++) {
for (int j = 0; j < vertices; j++) {
graph->adjMatrix[i * vertices + j] = 0;
}
}
}
// 判断无向图
int isUndirected(GraphAdjMat graph, int u, int v) {
return graph.adjMatrix[u * graph.vertices + v] && graph.adjMatrix[v * graph.vertices + u];
}
```
2. **邻接表**:
```c
typedef struct Node {
int vertex;
struct Node* next;
} Node;
typedef struct {
int vertices;
Node** adjacencyList; // 存储每个顶点的邻居列表
} GraphAdjList;
// 初始化邻接表
void initAdjList(GraphAdjList* graph, int vertices) {
graph->vertices = vertices;
graph->adjacencyList = malloc(sizeof(Node*) * vertices);
for (int i = 0; i < vertices; i++) {
graph->adjacencyList[i] = NULL;
}
}
// 求顶点的度
int degree(GraphAdjList graph, int vertex) {
int count = 0;
Node* curr = graph.adjacencyList[vertex];
while (curr != NULL) {
count++;
curr = curr->next;
}
return count;
}
// 图的深度优先遍历(DFS)
void dfs(GraphAdjList graph, int start, void (*visit)(int)) {
Node* node = graph.adjacencyList[start];
visit(start);
while (node != NULL) {
visit(node->vertex);
node = node->next;
}
}
```
3. **基本操作示例(注意,邻接表示例仅适用于遍历操作)**:
```c
void printDegrees(GraphAdjList graph) {
for (int i = 0; i < graph.vertices; i++) {
printf("Vertex %d has degree %d\n", i, degree(graph, i));
}
}
void printIsUndirected(GraphAdjMat matrix, int u, int v) {
if (isUndirected(matrix, u, v)) {
printf("%d and %d are connected in the undirected graph.\n", u, v);
} else {
printf("%d and %d are not connected in the undirected graph.\n", u, v);
}
}
// 使用示例
GraphAdjMat matrix = {10};
GraphAdjList list = {10};
// 初始化并填充数据...
```
阅读全文
相关推荐


















