中文字幕av专区_日韩电影在线播放_精品国产精品久久一区免费式_av在线免费观看网站

溫馨提示×

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
阜宁县| 德兴市| 清河县| 秦皇岛市| 灌阳县| 时尚| 拜城县| 华亭县| 长武县| 华坪县| 利津县| 灵宝市| 永嘉县| 平安县| 奉化市| 合川市| 张家川| 博白县| 吉隆县| 玉环县| 诸暨市| 汶上县| 新邵县| 广水市| 聊城市| 肇源县| 大庆市| 北宁市| 乾安县| 繁峙县| 鄯善县| 天气| 永仁县| 邻水| 含山县| 唐海县| 临江市| 锦屏县| 连云港市| 新平| 南平市|