引言图是一种非常强大的数据结构,广泛应用于计算机科学、网络、人工智能等领域。在C语言中实现图,不仅可以加深我们对数据结构的理解,还能提高编程能力。本文将带您深入了解C语言中图的实现方法,包括图的基本概...
图是一种非常强大的数据结构,广泛应用于计算机科学、网络、人工智能等领域。在C语言中实现图,不仅可以加深我们对数据结构的理解,还能提高编程能力。本文将带您深入了解C语言中图的实现方法,包括图的基本概念、数据结构以及常见的图算法。
图是由顶点(Vertex)和边(Edge)组成的集合。顶点代表图中的实体,边代表实体之间的关系。
#define MAX_VERTICES 100
typedef struct { int adjMatrix[MAX_VERTICES][MAX_VERTICES]; int numVertices;
} Graph;
// 初始化图
void initGraph(Graph *g, int numVertices) { g->numVertices = numVertices; for (int i = 0; i < numVertices; i++) { for (int j = 0; j < numVertices; j++) { g->adjMatrix[i][j] = 0; } }
}
// 添加边
void addEdge(Graph *g, int start, int end) { g->adjMatrix[start][end] = 1; g->adjMatrix[end][start] = 1; // 对于无向图
}#include
#include
typedef struct Node { int vertex; struct Node* next;
} Node;
typedef struct { int numVertices; Node** adjLists;
} Graph;
// 创建节点
Node* createNode(int v) { Node* newNode = (Node*)malloc(sizeof(Node)); newNode->vertex = v; newNode->next = NULL; return newNode;
}
// 创建图
Graph* createGraph(int vertices) { Graph* graph = (Graph*)malloc(sizeof(Graph)); graph->numVertices = vertices; graph->adjLists = (Node**)malloc(vertices * sizeof(Node*)); for (int i = 0; i < vertices; i++) { graph->adjLists[i] = NULL; } return graph;
}
// 添加边
void addEdge(Graph* graph, int src, int dest) { // 添加从src到dest的边 Node* newNode = createNode(dest); newNode->next = graph->adjLists[src]; graph->adjLists[src] = newNode; // 对于无向图,添加从dest到src的边 newNode = createNode(src); newNode->next = graph->adjLists[dest]; graph->adjLists[dest] = newNode;
} void DFS(Graph* graph, int vertex) { Node* adjList = graph->adjLists[vertex]; Node* temp = adjList; printf("访问顶点:%d\n", vertex); while (temp) { int connectedVertex = temp->vertex; if (visited[connectedVertex] == 0) { visited[connectedVertex] = 1; DFS(graph, connectedVertex); } temp = temp->next; }
}void BFS(Graph* graph, int startVertex) { Node* adjList; Node* temp; int* visited = (int*)malloc(graph->numVertices * sizeof(int)); for (int i = 0; i < graph->numVertices; i++) { visited[i] = 0; } visited[startVertex] = 1; int queue[graph->numVertices]; int front = 0; int rear = -1; queue[++rear] = startVertex; while (front <= rear) { int currentVertex = queue[front++]; printf("访问顶点:%d\n", currentVertex); adjList = graph->adjLists[currentVertex]; temp = adjList; while (temp) { int adjVertex = temp->vertex; if (visited[adjVertex] == 0) { visited[adjVertex] = 1; queue[++rear] = adjVertex; } temp = temp->next; } } free(visited);
}本文介绍了C语言中图的实现方法,包括邻接矩阵和邻接表表示法,以及常见的图算法(DFS和BFS)。通过学习这些内容,读者可以更好地理解图的基本概念和图算法的应用。在实际项目中,合理选择图的表示方法和算法可以提高程序的性能和可读性。