DATA STRUCTURES PROGRAM • GRAPHS

Topologically Sort a DAG with DFS

Learn how to topologically sort a dag with dfs using a clear C program.

IntermediateTopological sortDFSFinish time

PROBLEM UNDERSTANDING

Input and expected output

Sample input
No input required
Sample output
5 4 2 3 1 0

COMPLETE C PROGRAM

Complete C implementation

dsa-topological-sort-dfs.c
Open in compiler
#include <stdio.h>

void topo(int vertex, int graph[6][6], int visited[6], int stack[6], int *top)
{
    visited[vertex] = 1;
    for (int neighbour = 0; neighbour < 6; neighbour++)
        if (graph[vertex][neighbour] && !visited[neighbour]) topo(neighbour, graph, visited, stack, top);
    stack[(*top)++] = vertex;
}

int main(void)
{
    int graph[6][6] = {{0}};
    int edges[][2] = {{5,2},{5,0},{4,0},{4,1},{2,3},{3,1}};
    for (int index = 0; index < 6; index++) graph[edges[index][0]][edges[index][1]] = 1;
    int visited[6] = {0}, stack[6], top = 0;
    for (int vertex = 0; vertex < 6; vertex++)
        if (!visited[vertex]) topo(vertex, graph, visited, stack, &top);
    while (top > 0) printf("%d ", stack[--top]);
    putchar('\n');
    return 0;
}

GUIDED CODE TOUR • NOT LIVE EXECUTION

Study the program line by line

Use the real compiler button above to run and debug with different inputs.

CURRENT STEP

Select Start to walk through the important lines.

SELECTED LINE

No line selected

EXPECTED OUTPUT FOR THE SAMPLE

5 4 2 3 1 0
0%Step 0 of 0

PROGRAM EXPLANATION

Algorithm and explanation

  1. Read the required input values.
  2. Push each vertex after all descendants finish, then reverse the finish order.
  3. Display the computed result.

Push each vertex after all descendants finish, then reverse the finish order.

EFFICIENCY

Time and space complexity

Time complexity

O(V²) with matrix

Auxiliary space

O(V)

DEBUGGING CHECKLIST

Common mistakes

Check this

Use the correct format specifier for every variable.

Check this

Initialize variables before using their values.

Check this

Check braces, semicolons and input order carefully.

Try it yourself

Practice: Run the program with the sample input, predict its output, and then test one boundary case of your own.