c语言

C语言拓扑排序代码怎么写

小亿
108
2023-12-15 09:45:28
栏目: 编程语言

下面是一个用C语言实现拓扑排序的示例代码:

#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;
}

这个代码中,首先定义了一个结构体Graph来表示图,其中vertices表示顶点的个数,edges表示边的个数,adjacencyMatrix表示邻接矩阵。

然后定义了几个函数来操作图,包括initializeGraph用于初始化图,addEdge用于添加边,topologicalSortUtil用于递归实现拓扑排序,topologicalSort用于调用topologicalSortUtil进行拓扑排序。

main函数中,首先获取用户输入的顶点个数和边的个数,然后通过addEdge函数添加边,最后调用topologicalSort函数进行拓扑排序。

注意:该示例代码中使用邻接矩阵来表示图,适用于边数较少的情况。如果边数较多,推荐使用邻接表来表示图。

0
看了该问题的人还看了