亚洲激情专区-91九色丨porny丨老师-久久久久久久女国产乱让韩-国产精品午夜小视频观看

溫馨提示×

C語言拓撲排序代碼怎么寫

小億
93
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
遵义县| 宜昌市| 思南县| 宁陕县| 融水| 白银市| 和林格尔县| 涿鹿县| 石柱| 抚州市| 南郑县| 苏尼特左旗| 兰考县| 绵阳市| 子洲县| 黄浦区| 荆门市| 临夏市| 库尔勒市| 天津市| 阳春市| 阿鲁科尔沁旗| 康平县| 巍山| 南充市| 东阿县| 兰西县| 新余市| 贵港市| 手机| 昌黎县| 秦皇岛市| 射阳县| 城口县| 石渠县| 连山| 嘉黎县| 聊城市| 高青县| 湟中县| 三台县|