DATA STRUCTURES PROGRAM • GRAPHS

Topologically Sort a DAG with Kahn's Algorithm

Learn how to topologically sort a dag with kahn's algorithm using a clear C program.

IntermediateTopological sortIndegreeQueue

PROBLEM UNDERSTANDING

Input and expected output

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

COMPLETE C PROGRAM

Complete C implementation

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

int main(void)
{
    int graph[6][6] = {{0}};
    int edges[][2] = {{5,2},{5,0},{4,0},{4,1},{2,3},{3,1}};
    int indegree[6] = {0};
    for (int index = 0; index < 6; index++) {
        graph[edges[index][0]][edges[index][1]] = 1;
        indegree[edges[index][1]]++;
    }
    int queue[6], front = 0, rear = 0;
    for (int vertex = 0; vertex < 6; vertex++) if (indegree[vertex] == 0) queue[rear++] = vertex;
    while (front < rear) {
        int vertex = queue[front++]; printf("%d ", vertex);
        for (int neighbour = 0; neighbour < 6; neighbour++)
            if (graph[vertex][neighbour] && --indegree[neighbour] == 0) queue[rear++] = neighbour;
    }
    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

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

PROGRAM EXPLANATION

Algorithm and explanation

  1. Read the required input values.
  2. Repeatedly remove zero-indegree vertices and reduce the indegrees of their outgoing neighbours.
  3. Display the computed result.

Repeatedly remove zero-indegree vertices and reduce the indegrees of their outgoing neighbours.

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.