#include <stdio.h> #include <stdlib.h>

#define MAX_BOOKS 5

void addEdge(int graph[][MAX_BOOKS], int src, int dest) { if (src < MAX_BOOKS && dest < MAX_BOOKS) { graph[src][dest] = 1; } }

void topologicalSortUtil(int graph[][MAX_BOOKS], int v, int visited[], int* stack, int* stackIndex) { visited[v] = 1;

for (int i = 1; i &#x3C;= MAX_BOOKS; i++) {
    if (graph[v][i] &#x26;&#x26; !visited[i]) {
        topologicalSortUtil(graph, i, visited, stack, stackIndex);
    }
}

stack[(*stackIndex)++] = v;

}

void topologicalSort(int graph[][MAX_BOOKS]) { int visited[MAX_BOOKS] = {0}; int stack[MAX_BOOKS]; int stackIndex = 0;

for (int i = 0; i &#x3C; MAX_BOOKS; i++) {
    if (!visited[i]) {
        topologicalSortUtil(graph, i, visited, stack, &#x26;stackIndex);
    }
}

printf("借阅书籍的顺序:\n");
while (stackIndex &#x3E; 0) {
    printf("%d. &#x3C;书籍%d&#x3E;\n", MAX_BOOKS - stackIndex + 1, stack[--stackIndex] + 1);
}

}

int main() { int graph[MAX_BOOKS][MAX_BOOKS] = {0};

addEdge(graph, 4, 0);  // &#x3C;数据结构与算法&#x3E; 依赖于 &#x3C;编译原理&#x3E;
addEdge(graph, 0, 1);  // &#x3C;计算机网络&#x3E; 依赖于 &#x3C;数据结构与算法&#x3E;
addEdge(graph, 2, 1);  // &#x3C;计算机网络&#x3E; 依赖于 &#x3C;数据库系统&#x3E;
addEdge(graph, 4, 2);  // &#x3C;数据库系统&#x3E; 依赖于 &#x3C;编译原理&#x3E;
addEdge(graph, 1, 3);  // &#x3C;操作系统&#x3E; 依赖于 &#x3C;计算机网络&#x3E;
addEdge(graph, 2, 3);  // &#x3C;操作系统&#x3E; 依赖于 &#x3C;数据库系统&#x3E;

topologicalSort(graph);

return 0;

}


原文地址: https://www.cveoy.top/t/topic/pL74 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录