C语言实现拓扑排序算法解决书籍借阅顺序问题
#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 <= MAX_BOOKS; i++) {
if (graph[v][i] && !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 < MAX_BOOKS; i++) {
if (!visited[i]) {
topologicalSortUtil(graph, i, visited, stack, &stackIndex);
}
}
printf("借阅书籍的顺序:\n");
while (stackIndex > 0) {
printf("%d. <书籍%d>\n", MAX_BOOKS - stackIndex + 1, stack[--stackIndex] + 1);
}
}
int main() { int graph[MAX_BOOKS][MAX_BOOKS] = {0};
addEdge(graph, 4, 0); // <数据结构与算法> 依赖于 <编译原理>
addEdge(graph, 0, 1); // <计算机网络> 依赖于 <数据结构与算法>
addEdge(graph, 2, 1); // <计算机网络> 依赖于 <数据库系统>
addEdge(graph, 4, 2); // <数据库系统> 依赖于 <编译原理>
addEdge(graph, 1, 3); // <操作系统> 依赖于 <计算机网络>
addEdge(graph, 2, 3); // <操作系统> 依赖于 <数据库系统>
topologicalSort(graph);
return 0;
}
原文地址: https://www.cveoy.top/t/topic/pL74 著作权归作者所有。请勿转载和采集!