算法竞赛入门经典中深搜拓扑排序的实现
#include
#include
#define maxn 20
int vis[maxn];
int topo[maxn];
int t, n;
int adj[maxn][maxn];
int dfs(int u){
int v;
vis[u] = -1;
for(int v = 1; v <= n; ++v){
if(adj[u][v]){
if(vis[v] < 0) return 0;
if(!vis[v] && !dfs(v)) return 0;
}
}
vis[u] = 1;
topo[--t] = u;
return 1;
}
int toposort(){
int u;
memset(vis, 0, sizeof(vis));
t = n;
for(u = 1; u <= n; ++u)
if(!vis[u])
if(!dfs(u)) return 0;;
return 1;
}
void createGraphic(){
int i, e;
memset(adj, 0, sizeof(adj));
printf("please input n and e:");
scanf("%d%d", &n, &e);
printf("please input the edges:\n");
for(i = 1; i <= e; ++i){
int a, b;
scanf("%d%d", &a, &b);
adj[a][b] = 1;
}
}
int main(){
int i;
createGraphic();
toposort();
for(i = 0; i < n; ++i)
printf("%d ", topo[i]);
printf("\n");
return 0;
}