下面是一個(gè)用C語言實(shí)現(xiàn)拓?fù)渑判虻氖纠a:
#include <stdio.h>
#include <stdbool.h>
#define MAXVERTICES 100
struct Graph {
int vertices;
int edges;
int adjacencyMatrix[MAXVERTICES][MAXVERTICES];
};
void initializeGraph(struct Graph* graph, int vertices) {
graph->vertices = vertices;
graph->edges = 0;
for (int i = 0; i < vertices; i++) {
for (int j = 0; j < vertices; j++) {
graph->adjacencyMatrix[i][j] = 0;
}
}
}
void addEdge(struct Graph* graph, int startVertex, int endVertex) {
graph->adjacencyMatrix[startVertex][endVertex] = 1;
graph->edges++;
}
void topologicalSortUtil(struct Graph* graph, int vertex, bool visited[], int stack[], int* stackIndex) {
visited[vertex] = true;
for (int i = 0; i < graph->vertices; i++) {
if (graph->adjacencyMatrix[vertex][i] == 1 && !visited[i]) {
topologicalSortUtil(graph, i, visited, stack, stackIndex);
}
}
stack[(*stackIndex)++] = vertex;
}
void topologicalSort(struct Graph* graph) {
bool visited[MAXVERTICES] = {false};
int stack[MAXVERTICES];
int stackIndex = 0;
for (int i = 0; i < graph->vertices; i++) {
if (!visited[i]) {
topologicalSortUtil(graph, i, visited, stack, &stackIndex);
}
}
printf("Topological Sort: ");
while (stackIndex > 0) {
printf("%d ", stack[--stackIndex]);
}
printf("\n");
}
int main() {
struct Graph graph;
int vertices, edges, startVertex, endVertex;
printf("Enter the number of vertices in the graph: ");
scanf("%d", &vertices);
initializeGraph(&graph, vertices);
printf("Enter the number of edges in the graph: ");
scanf("%d", &edges);
for (int i = 0; i < edges; i++) {
printf("Enter the start and end vertex of edge %d: ", i + 1);
scanf("%d %d", &startVertex, &endVertex);
addEdge(&graph, startVertex, endVertex);
}
topologicalSort(&graph);
return 0;
}
這個(gè)代碼中,首先定義了一個(gè)結(jié)構(gòu)體Graph
來表示圖,其中vertices
表示頂點(diǎn)的個(gè)數(shù),edges
表示邊的個(gè)數(shù),adjacencyMatrix
表示鄰接矩陣。
然后定義了幾個(gè)函數(shù)來操作圖,包括initializeGraph
用于初始化圖,addEdge
用于添加邊,topologicalSortUtil
用于遞歸實(shí)現(xiàn)拓?fù)渑判颍?code>topologicalSort用于調(diào)用topologicalSortUtil
進(jìn)行拓?fù)渑判颉?/p>
在main
函數(shù)中,首先獲取用戶輸入的頂點(diǎn)個(gè)數(shù)和邊的個(gè)數(shù),然后通過addEdge
函數(shù)添加邊,最后調(diào)用topologicalSort
函數(shù)進(jìn)行拓?fù)渑判颉?/p>
注意:該示例代碼中使用鄰接矩陣來表示圖,適用于邊數(shù)較少的情況。如果邊數(shù)較多,推薦使用鄰接表來表示圖。