Beispiel #1
0
void topo_dfs (int node) {
    vis[node] = 1;
    for (int i = 1; i <= n; ++i) {
        if (map[node][i] && !vis[i]) {
            topo_dfs(i);
        }
    }
    topo_list[++cnt_topo_list] = node;
}
Beispiel #2
0
void topo_sort (void) {
    memset(topo_list, 0, sizeof(topo_list));
    cnt_topo_list = 0;
    memset(vis, 0, sizeof(vis));
    for (int i = 1; i <= n; ++i) {
        if (!vis[i]) {
            topo_dfs(i);
        }
    }
}
int main()
{
    int n1, n2, i;
    int* tptr;

    /* read in the number of nodes */
    scanf( "%d", &numNodes );
    
    /* initialize */
    for ( i = 0; i < numNodes; i++ )
    {
	allNodes[i].numAdj = 0;
	allNodes[i].adj = NULL;
	val[i] = 0;
    }

    /* read in the edges in the dag */
    while( scanf( "%d%d", &n1, &n2 ) == 2 )
    {
	tptr = realloc( allNodes[n1].adj, 
			allNodes[n1].numAdj * sizeof( int ) );
	if ( !tptr )
	{
	    fprintf( stderr, "Out of memory, exiting.\n" );
	    exit( 1 );
	}
	allNodes[n1].adj = tptr;
	allNodes[n1].adj[allNodes[n1].numAdj++] = n2;
    }

    /* MUST INITIALIZE topoIndex to the end of the topo array */
    topoIndex = numNodes - 1;

    /* call the dfs procedure on each connected component */
    for ( i = 0; i < numNodes; i++ )
    {
	if ( !val[i] )
	{
	    topo_dfs( i );
	}
    }

    /* print out the results */
    for ( i = 0; i < numNodes; i++ )
    {
	printf( "%d ", topo[i] );
    }    
    printf( "\n" );

    return 0;
}
void topo_dfs( int k )
{
    int next;

    /* mark this node as having been visited */
    val[k] = ++id;

    /* look at all nodes adjecent to the current node */
    for ( next = 0; next < allNodes[k].numAdj; next++ )
    {
	if ( !val[allNodes[k].adj[next]] )
	{
	    /* recurse if the node has not been visited before */
	    topo_dfs( allNodes[k].adj[next] );
	}
    }

    /* the current node is adjacent to no more unvisited nodes, so put
       it in the list, in the unused position closest to the end */
    topo[topoIndex--] = k;
}