Topological Sort Using DFS

Problem and examples

Topological Sort is a linear ordering of vertices in a directed graph such that for every directed edge u → v, vertex u comes before v in the ordering.

It is only applicable to Directed Acyclic Graphs (DAGs) and is used in scenarios like task scheduling, build systems, and dependency resolution.

Graph (Edges) Topological Sort Description
0 → 1, 0 → 2, 1 → 3, 2 → 3 0 → 2 → 1 → 3 Multiple valid orderings possible, DFS pushes deeper nodes first
5 → 0, 5 → 2, 4 → 0, 4 → 1, 2 → 3, 3 → 1 5 → 4 → 2 → 3 → 1 → 0 Topological sort based on dependencies
1 → 2, 2 → 3 1 → 2 → 3 Straightforward chain
None Any order Empty graph or no edges
0 → 1, 1 → 2, 2 → 0 Not possible Cycle detected, not a DAG

How it works

Understanding the Problem

Topological sorting is a way of arranging the nodes of a directed graph in a linear order such that for every directed edge u → v, node u comes before node v in the ordering.

This type of sorting is only possible if the graph is a Directed Acyclic Graph (DAG), meaning it has no cycles. It's commonly used in scenarios like task scheduling, where one task must be completed before another, or in resolving build dependencies.

Step-by-Step Solution with Example

step 1: Represent the Graph

We begin by representing the graph using an adjacency list. This structure allows us to keep track of all nodes and their direct dependencies.


Graph:
A → B
B → C
A → C
Adjacency List:
{
  A: [B, C],
  B: [C],
  C: []
}

step 2: Initialize Required Data Structures

We use a visited set to track visited nodes and a stack to store the topological order as we finish visiting each node’s dependencies.

step 3: Perform DFS from Each Unvisited Node

We perform a Depth-First Search (DFS) starting from each unvisited node. In DFS, we go deeper into the graph until we reach nodes with no outgoing edges, then we add those to our stack as we backtrack.

step 4: Push Nodes to Stack After Exploring All Neighbors

Once we finish visiting all neighbors of a node, we push it to the stack. This ensures that nodes with no dependencies are added first, and their dependents come later in the final order.

step 5: Reverse the Stack to Get the Topological Order

Since the first node we complete is the one with no outgoing edges, we reverse the stack to get the correct topological order from start to finish.

step 6: Apply the Steps to Our Example

Let’s apply this to our earlier example:

  • Start DFS from A → visit B → visit C
  • Push C to stack (C has no neighbors)
  • Backtrack to B → all neighbors visited → push B
  • Backtrack to A → all neighbors visited → push A

Stack (before reversing): [C, B, A]

Final Topological Order (after reversing): A, B, C

Edge Cases

Disconnected Graph Components

If the graph has disconnected components (not all nodes are reachable from a single starting point), we must initiate DFS from every unvisited node to ensure all components are included in the result.

Already Sorted Graph

If the graph already has nodes arranged in a valid topological order, the algorithm still works correctly and preserves the order after processing.

Cycle in Graph

If the graph contains a cycle (e.g., A → B → C → A), then topological sorting is not possible. A DFS-based approach needs an extra mechanism, like tracking nodes in the recursion stack, to detect cycles and prevent incorrect results.

Finally

Topological sort using DFS is a powerful technique to handle task sequencing problems in graphs. By understanding how DFS backtracks and uses a stack, we can ensure correct ordering of tasks based on dependencies. However, always verify that the input graph is acyclic, as cycles make topological sorting invalid.

This step-by-step approach builds intuition for beginners and prepares you to handle both regular and edge-case scenarios effectively.

  1. Initialize a visited set and a stack (for order).
  2. Define a recursive dfs(node):
    • Mark node as visited.
    • For each neighbor of node:
      • If not visited, call dfs(neighbor).
    • After visiting all neighbors, push node to stack.
  3. Call dfs on all unvisited nodes.
  4. Reverse the stack to get the topological order.

Implementation and efficiency

C implementation

#include <stdio.h>
#include <stdlib.h>
#define MAX 6

int graph[MAX][MAX] = {
    {0, 0, 0, 0, 0, 0},
    {0, 0, 0, 1, 0, 0},
    {0, 0, 0, 1, 0, 0},
    {0, 0, 0, 0, 1, 0},
    {0, 0, 0, 0, 0, 1},
    {0, 0, 0, 0, 0, 0}
};
int visited[MAX] = {0};
int stack[MAX];
int top = -1;

void dfs(int node) {
    visited[node] = 1;
    for (int i = 0; i < MAX; i++) {
        if (graph[node][i] && !visited[i]) {
            dfs(i);
        }
    }
    stack[++top] = node;
}

int main() {
    for (int i = 0; i < MAX; i++) {
        if (!visited[i]) {
            dfs(i);
        }
    }
    printf("Topological Sort: ");
    while (top >= 0) {
        printf("%d ", stack[top--]);
    }
    return 0;
}

C++ implementation

#include <iostream>
#include <vector>
#include <stack>
using namespace std;

void dfs(int node, vector<bool>& visited, stack<int>& st, vector<vector<int>>& graph) {
    visited[node] = true;
    for (int neighbor : graph[node]) {
        if (!visited[neighbor]) {
            dfs(neighbor, visited, st, graph);
        }
    }
    st.push(node);
}

int main() {
    vector<vector<int>> graph = {{}, {}, {3}, {1}, {0, 1}, {0, 2}};
    vector<bool> visited(6, false);
    stack<int> st;

    for (int i = 0; i < 6; i++) {
        if (!visited[i]) {
            dfs(i, visited, st, graph);
        }
    }

    cout << "Topological Sort: ";
    while (!st.empty()) {
        cout << st.top() << " ";
        st.pop();
    }
    return 0;
}

Python implementation

def dfs(node, visited, stack, graph):
    visited.add(node)
    for neighbor in graph.get(node, []):
        if neighbor not in visited:
            dfs(neighbor, visited, stack, graph)
    stack.append(node)

graph = {
    5: [0, 2],
    4: [0, 1],
    2: [3],
    3: [1],
    0: [],
    1: []
}

visited = set()
stack = []

for node in graph:
    if node not in visited:
        dfs(node, visited, stack, graph)

print("Topological Sort:", stack[::-1])

Java implementation

import java.util.*;

public class TopologicalSort {
    public static void dfs(int node, boolean[] visited, Stack<Integer> stack, Map<Integer, List<Integer>> graph) {
        visited[node] = true;
        for (int neighbor : graph.getOrDefault(node, new ArrayList<>())) {
            if (!visited[neighbor]) {
                dfs(neighbor, visited, stack, graph);
            }
        }
        stack.push(node);
    }

    public static void main(String[] args) {
        Map<Integer, List<Integer>> graph = new HashMap<>();
        graph.put(5, Arrays.asList(0, 2));
        graph.put(4, Arrays.asList(0, 1));
        graph.put(2, Arrays.asList(3));
        graph.put(3, Arrays.asList(1));
        graph.put(0, new ArrayList<>());
        graph.put(1, new ArrayList<>());

        boolean[] visited = new boolean[6];
        Stack<Integer> stack = new Stack<>();

        for (int i = 0; i < 6; i++) {
            if (!visited[i]) {
                dfs(i, visited, stack, graph);
            }
        }

        System.out.print("Topological Sort: ");
        while (!stack.isEmpty()) {
            System.out.print(stack.pop() + " ");
        }
    }
}

JavaScript implementation

function topologicalSort(graph) {
  const visited = new Set();
  const stack = [];

  function dfs(node) {
    visited.add(node);
    for (const neighbor of graph[node] || []) {
      if (!visited.has(neighbor)) {
        dfs(neighbor);
      }
    }
    stack.push(node);
  }

  for (const node in graph) {
    if (!visited.has(Number(node))) {
      dfs(Number(node));
    }
  }

  return stack.reverse();
}

const graph = {
  5: [0, 2],
  4: [0, 1],
  2: [3],
  3: [1],
  0: [],
  1: []
};

console.log("Topological Sort:", topologicalSort(graph));

Go implementation

package main

import (
    "fmt"
)

func dfs(node int, visited []bool, stack *[]int, graph map[int][]int) {
    visited[node] = true
    for _, neighbor := range graph[node] {
        if !visited[neighbor] {
            dfs(neighbor, visited, stack, graph)
        }
    }
    *stack = append(*stack, node)
}

func main() {
    graph := map[int][]int{
        5: {0, 2},
        4: {0, 1},
        2: {3},
        3: {1},
        0: {},
        1: {},
    }
    visited := make([]bool, 6)
    var stack []int

    for i := 0; i < 6; i++ {
        if !visited[i] {
            dfs(i, visited, &stack, graph)
        }
    }

    for i := len(stack) - 1; i >= 0; i-- {
        fmt.Print(stack[i], " ")
    }
}

Rust implementation

use std::collections::{HashMap, HashSet};

fn dfs(node: i32, graph: &HashMap<i32, Vec<i32>>, visited: &mut HashSet<i32>, stack: &mut Vec<i32>) {
    visited.insert(node);
    if let Some(neighbors) = graph.get(&node) {
        for &neighbor in neighbors {
            if !visited.contains(&neighbor) {
                dfs(neighbor, graph, visited, stack);
            }
        }
    }
    stack.push(node);
}

fn main() {
    let graph = HashMap::from([
        (5, vec![0, 2]),
        (4, vec![0, 1]),
        (2, vec![3]),
        (3, vec![1]),
        (0, vec![]),
        (1, vec![]),
    ]);

    let mut visited = HashSet::new();
    let mut stack = Vec::new();

    for &node in graph.keys() {
        if !visited.contains(&node) {
            dfs(node, &graph, &mut visited, &mut stack);
        }
    }

    stack.reverse();
    println!("Topological Sort: {:?}", stack);
}

Kotlin implementation

fun dfs(node: Int, visited: BooleanArray, stack: MutableList<Int>, graph: Map<Int, List<Int>>) {
    visited[node] = true
    for (neighbor in graph[node] ?: emptyList()) {
        if (!visited[neighbor]) {
            dfs(neighbor, visited, stack, graph)
        }
    }
    stack.add(node)
}

fun main() {
    val graph = mapOf(
        5 to listOf(0, 2),
        4 to listOf(0, 1),
        2 to listOf(3),
        3 to listOf(1),
        0 to listOf(),
        1 to listOf()
    )
    val visited = BooleanArray(6)
    val stack = mutableListOf<Int>()

    for (i in 0..5) {
        if (!visited[i]) {
            dfs(i, visited, stack, graph)
        }
    }

    println("Topological Sort: ${stack.reversed()}")
}

Swift implementation

func dfs(_ node: Int, _ graph: [Int: [Int]], _ visited: inout [Bool], _ stack: inout [Int]) {
    visited[node] = true
    for neighbor in graph[node] ?? [] {
        if !visited[neighbor] {
            dfs(neighbor, graph, &visited, &stack)
        }
    }
    stack.append(node)
}

let graph: [Int: [Int]] = [
    5: [0, 2],
    4: [0, 1],
    2: [3],
    3: [1],
    0: [],
    1: []
]

var visited = Array(repeating: false, count: 6)
var stack: [Int] = []

for node in 0...5 {
    if !visited[node] {
        dfs(node, graph, &visited, &stack)
    }
}

print("Topological Sort:", stack.reversed())

TypeScript implementation

function topologicalSort(graph: Record<number, number[]>): number[] {
  const visited = new Set<number>();
  const stack: number[] = [];

  function dfs(node: number): void {
    visited.add(node);
    for (const neighbor of graph[node] || []) {
      if (!visited.has(neighbor)) {
        dfs(neighbor);
      }
    }
    stack.push(node);
  }

  for (const node in graph) {
    const numNode = Number(node);
    if (!visited.has(numNode)) {
      dfs(numNode);
    }
  }

  return stack.reverse();
}

const graph: Record<number, number[]> = {
  5: [0, 2],
  4: [0, 1],
  2: [3],
  3: [1],
  0: [],
  1: []
};

console.log("Topological Sort:", topologicalSort(graph));

Time complexity

CaseTimeExplanation
best caseO(V + E)Even in the best case, each vertex and its edges must be visited to ensure proper order.
average caseO(V + E)Every node is visited once and all its outgoing edges are checked once during DFS.
worst caseO(V + E)In the worst case, the graph is dense, and all vertices and edges must be processed.

Space complexity

O(V + E)

We use a visited set (O(V)), a stack (O(V)), and an adjacency list (O(V + E)) to represent the graph.