AlgoTales · Roadmap

DFS-based topological sort

Advanced · 9 min · code in PHP, JavaScript, Java and Go

Where you will meet this in real life

This way of ordering tasks follows dependencies down as far as possible with DFS and writes each item down only after everything it needs is already written. Reading the list backwards, or building it in that order, gives a safe sequence.

Practical use cases

  • Web app: Resolving import order in a JavaScript bundle. A build tool sees that app.js needs cart.js, which needs utils.js. It dives to utils.js first and records finished files as it comes back, so the final bundle has files in an order where every file's needs appear above it.
  • Web app: Laravel service container setup. A framework must create services such as Mailer, which needs Config and Logger. Creating each service after diving into its needs and finishing them ensures everything is ready when asked for. If a service needs itself through a chain, the same walk notices it is already in progress and reports a clear loop error.
  • Web app: Study planner for a topic list. A learning app lists topics where each says "learn X first". Starting from the goal topic and diving into prerequisites produces a "learn in this order" list for the student.
  • System: Compilers and strongly connected parts. Compilers order declarations and linkers order modules this way, and the same finishing order is the first step of algorithms that find tangled groups. The finishing order is the key: something is only written down once everything it needs is already on the list, so the reversed list is always safe.

The story: The Last One Out Goes First

Zoya was packing for the family trip, and her suitcase was a mess. Her mother's rules: socks go on before shoes, the shoes go in before the bag is zipped, and the bag is zipped before the trip begins. Kahn's queue trick was one way to sort this out, but Zoya preferred to think like she was exploring a maze.

"Start with any item. Keep following its arrows deeper and deeper until you reach something that leads nowhere, like zip the bag. That one is at the very end of the chain, so I put it at the bottom of a pile. Then I step back one, and once everything after it is done, I put it on the pile too."

When she finished, her pile had the last jobs at the bottom and the first jobs at the top. She just turned the pile upside down, and there was her packing order. The trick: an item is never put on the pile until everything that must come after it is already on the pile. So reading the pile backwards never breaks a rule.

This is the DFS-based topological sort: run a depth-first search, record each node when it finishes, and reverse the finishing order.

How to spot this problem, and where you need it

You have items that depend on others, and you already have or like recursive depth-first code, and want a correct order without counting prerequisites.

Signs you need it

  • You naturally think "to do this, first do that, and to do that, first do another", which is recursion going down dependencies.
  • You start from a goal item and need everything required to reach it, in a safe order.
  • Cycles must be reported, and the data is stored as a list of neighbours for each item.

Where to use it in a project

  • Module, service or file loaders that resolve what a requested item needs before running it.
  • Tools that print a "do these in order" list for a chosen target, such as make-like or install scripts.

The solution

Run DFS from each unvisited node. When you finish a node, meaning all nodes it points to are done, push it onto a list. After all nodes are processed, reverse the list. In that reversed order each node appears before everything it points to. Mark nodes as "in progress" and "done"; reaching an in-progress node means a loop and the order is impossible.

Payoff: Before: manually reordering imports until the bundle stops throwing errors. After: a 15-line recursive function always produces a valid order.

Explain it like I am 8

Follow the arrows as deep as you can. When you get stuck, put that thing at the bottom of a pile. Come back and add things as they finish. Flip the pile at the end, and the order is perfect.

How it works, step by step

  1. Keep a state for each node: not visited, in progress (on the current path), or finished.
  2. Start a DFS from any unvisited node. Mark it in progress and visit its neighbours that are not yet visited.
  3. If you ever meet a neighbour that is in progress, you have found a cycle. There is no valid order.
  4. When a node has no more neighbours to explore, mark it finished and push it onto a list.
  5. After every node is visited, reverse the list. That is the topological order.

The code in four languages

PHP

<?php
// DFS-based topological sort. Returns null if the graph has a cycle.
function topoSort(array $adj): ?array {
    $n = count($adj);
    $state = array_fill(0, $n, 0);     // 0 = new, 1 = on current path, 2 = finished
    $finished = [];
    $hasCycle = false;

    $visit = function (int $u) use (&$visit, &$state, &$finished, &$hasCycle, $adj): void {
        $state[$u] = 1;
        foreach ($adj[$u] as $v) {
            if ($state[$v] === 1) { $hasCycle = true; }       // met someone on our own path
            elseif ($state[$v] === 0) { $visit($v); }
        }
        $state[$u] = 2;
        $finished[] = $u;               // everything after u is already finished
    };

    for ($i = 0; $i < $n; $i++) {
        if ($state[$i] === 0) $visit($i);
    }
    return $hasCycle ? null : array_reverse($finished);
}

$names = ['A', 'B', 'C', 'D', 'E', 'F'];
$adj = [[1, 2], [3], [3], [4], [], [2]];     // A->B, A->C, B->D, C->D, D->E, F->C
$order = topoSort($adj);
echo implode(' ', array_map(fn($i) => $names[$i], $order)) . PHP_EOL;
var_dump(topoSort([[1], [0]]));              // a loop: no answer

JavaScript

// DFS-based topological sort. Returns null if the graph has a cycle.
function topoSort(adj) {
  const n = adj.length;
  const state = new Array(n).fill(0);   // 0 = new, 1 = on current path, 2 = finished
  const finished = [];
  let hasCycle = false;

  function visit(u) {
    state[u] = 1;
    for (const v of adj[u]) {
      if (state[v] === 1) hasCycle = true;       // met someone on our own path
      else if (state[v] === 0) visit(v);
    }
    state[u] = 2;
    finished.push(u);                   // everything after u is already finished
  }

  for (let i = 0; i < n; i++) {
    if (state[i] === 0) visit(i);
  }
  return hasCycle ? null : finished.reverse();
}

const names = ['A', 'B', 'C', 'D', 'E', 'F'];
const adj = [[1, 2], [3], [3], [4], [], [2]];   // A->B, A->C, B->D, C->D, D->E, F->C
const order = topoSort(adj);
console.log(order.map(i => names[i]).join(' '));
console.log(topoSort([[1], [0]]));              // a loop: no answer

Java

import java.util.*;

public class Main {
    static int[] state;                 // 0 = new, 1 = on current path, 2 = finished
    static List<Integer> finished;
    static boolean hasCycle;

    // DFS-based topological sort. Returns null if the graph has a cycle.
    static List<Integer> topoSort(int[][] adj) {
        int n = adj.length;
        state = new int[n];
        finished = new ArrayList<>();
        hasCycle = false;
        for (int i = 0; i < n; i++) {
            if (state[i] == 0) visit(adj, i);
        }
        if (hasCycle) return null;
        Collections.reverse(finished);
        return finished;
    }

    static void visit(int[][] adj, int u) {
        state[u] = 1;
        for (int v : adj[u]) {
            if (state[v] == 1) hasCycle = true;       // met someone on our own path
            else if (state[v] == 0) visit(adj, v);
        }
        state[u] = 2;
        finished.add(u);                // everything after u is already finished
    }

    public static void main(String[] args) {
        String[] names = {"A", "B", "C", "D", "E", "F"};
        int[][] adj = {{1, 2}, {3}, {3}, {4}, {}, {2}};   // A->B, A->C, B->D, C->D, D->E, F->C
        List<String> words = new ArrayList<>();
        for (int i : topoSort(adj)) words.add(names[i]);
        System.out.println(String.join(" ", words));
        System.out.println(topoSort(new int[][]{{1}, {0}}));   // a loop: no answer (null)
    }
}

Go

package main

import (
	"fmt"
	"strings"
)

// topoSort is the DFS-based topological sort. It returns ok=false if the graph has a cycle.
func topoSort(adj [][]int) (order []int, ok bool) {
	n := len(adj)
	state := make([]int, n) // 0 = new, 1 = on current path, 2 = finished
	var finished []int
	hasCycle := false

	var visit func(u int)
	visit = func(u int) {
		state[u] = 1
		for _, v := range adj[u] {
			if state[v] == 1 {
				hasCycle = true // met someone on our own path
			} else if state[v] == 0 {
				visit(v)
			}
		}
		state[u] = 2
		finished = append(finished, u) // everything after u is already finished
	}

	for i := 0; i < n; i++ {
		if state[i] == 0 {
			visit(i)
		}
	}
	if hasCycle {
		return nil, false
	}
	for i := len(finished) - 1; i >= 0; i-- { // reverse the finishing order
		order = append(order, finished[i])
	}
	return order, true
}

func main() {
	names := []string{"A", "B", "C", "D", "E", "F"}
	adj := [][]int{{1, 2}, {3}, {3}, {4}, {}, {2}} // A->B, A->C, B->D, C->D, D->E, F->C
	order, _ := topoSort(adj)
	var words []string
	for _, i := range order {
		words = append(words, names[i])
	}
	fmt.Println(strings.Join(words, " "))
	if _, ok := topoSort([][]int{{1}, {0}}); !ok {
		fmt.Println("null") // a loop: no answer
	}
}

Time: O(V + E) · Extra space: O(V). A DFS touches every node and every arrow once. The recursion stack can be as deep as the longest path.

Watch out for

  • Forgetting to reverse the finished list. The un-reversed list is the exact opposite of what you want.
  • Using only a visited yes/no flag. Without the "in progress" state you cannot tell a harmless revisit from a cycle.
  • Starting the DFS from only one node. Loop over all nodes so disconnected parts are included.

Quick check

  1. When does a node get added to the finished list?
    • When its in-degree is 0
    • When we first enter it
    • After all the nodes it points to are finished
  2. How do you get the final topological order?
    • Sort the nodes alphabetically
    • Reverse the finished list
    • Use the finished list as it is
  3. During DFS you reach a neighbour that is still "in progress". What does it mean?
    • There is a cycle
    • We found the shortest path
    • The graph is a tree