91超碰碰碰碰久久久久久综合_超碰av人澡人澡人澡人澡人掠_国产黄大片在线观看画质优化_txt小说免费全本

溫馨提示×

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
南阳市| 富蕴县| 泗水县| 吴堡县| 泰和县| 柳河县| 天峻县| 阜康市| 荣昌县| 鹤壁市| 安阳县| 乐安县| 全州县| 郓城县| 灵丘县| 镇康县| 太保市| 沂南县| 紫金县| 广灵县| 华亭县| 双流县| 巴林右旗| 邳州市| 随州市| 攀枝花市| 富宁县| 砚山县| 深圳市| 桃江县| 宜兴市| 马公市| 儋州市| 镇赉县| 丰城市| 兴隆县| 大方县| 宜昌市| 吴桥县| 康马县| 太仓市|