/** This is topological sort for an acyclic graph An acyclic graph has no cycles m=out[i][0] is the number of edges from vertex i out[i][1], ..., out[i][m] are endpoints of edges from i Endpoints, namely edges, can be given in any order **/ int out[100][100]; int i, k, n, stack[100]; int visited[100]; char name[100]; dfs(int v) { int j,w,m; visited[v]=1; ; m=out[v][0]; for (j=1; j<=m; j++) { w=out[v][j]; if (visited[w]==0) { dfs(w); } } stack[k]=v; k++; // When we leave v, v is recorded into stack } main(){ /*** graph initialization. You can edit this part for any acyclic graph ***/ out[1][0]=2; out[1][1]=3; out[1][2]=2; out[2][0]=1; out[2][1]=3; out[2][2]=4; out[3][0]=1; out[3][1]=5; out[4][0]=1; out[4][1]=6; out[5][0]=2; out[5][1]=6; out[5][2]=4; out[6][0]=0; n=6; for(i=1;i<=n;i++)visited[i]=0; k=1; dfs(1); for(i=k-1;i>=1;i--)printf("%d ", stack[i]); printf("\n"); }