Topological sorting using Javascript DFS

A topological sort or topological ordering of a directed graph is a linear ordering of its vertices such that for every directed edge UV from vertex u to vertex v, u comes before v in the ordering. This only makes sense in directed acyclic graphs (DAGs).

There are many places where topological sort makes a lot of sense. For example, let's say you're following a recipe, in this, there are some steps that are prerequisites for going to the next steps. Similarly, during college when selecting courses, there are prerequisites for more advanced courses which themselves may be prerequisites for further courses.

Course Prerequisite Example

CS101 CS102 CS204 CS340 CS380 CS410 CS540

Following are some possible topological sorts for the above graph:

CS101 ? CS204 ? CS102 ? CS340 ? CS410 ? CS380 ? CS540
CS102 ? CS101 ? CS340 ? CS204 ? CS410 ? CS380 ? CS540

Implementation Using DFS

Let's implement topological sorting using Depth-First Search (DFS). We'll need a Graph class and a Stack for storing the sorted order:

class Stack {
    constructor() {
        this.items = [];
    }
    
    push(item) {
        this.items.push(item);
    }
    
    pop() {
        return this.items.pop();
    }
    
    isEmpty() {
        return this.items.length === 0;
    }
}

class Graph {
    constructor() {
        this.nodes = [];
        this.edges = {};
    }
    
    addNode(node) {
        this.nodes.push(node);
        this.edges[node] = [];
    }
    
    addDirectedEdge(from, to) {
        this.edges[from].push(to);
    }
    
    topologicalSortHelper(node, explored, s) {
        explored.add(node);
        
        // Visit all dependent nodes first
        this.edges[node].forEach(n => {
            if (!explored.has(n)) {
                this.topologicalSortHelper(n, explored, s);
            }
        });
        
        // Add current node to stack after all dependencies are processed
        s.push(node);
    }

    topologicalSort() {
        let s = new Stack();
        let explored = new Set();

        // Process all unvisited nodes
        this.nodes.forEach(node => {
            if (!explored.has(node)) {
                this.topologicalSortHelper(node, explored, s);
            }
        });

        // Print sorted order
        const result = [];
        while (!s.isEmpty()) {
            result.push(s.pop());
        }
        return result;
    }
}

Complete Example

// Create and populate the graph
let g = new Graph();
g.addNode("A");
g.addNode("B");
g.addNode("C");
g.addNode("D");
g.addNode("E");
g.addNode("F");
g.addNode("G");

g.addDirectedEdge("A", "C");
g.addDirectedEdge("A", "B");
g.addDirectedEdge("A", "D");
g.addDirectedEdge("C", "D");
g.addDirectedEdge("D", "E");
g.addDirectedEdge("E", "F");
g.addDirectedEdge("B", "G");

// Perform topological sort
const sorted = g.topologicalSort();
console.log("Topological Sort Order:");
sorted.forEach(node => console.log(node));

Graph Visualization

A C B D G E F

Output

Topological Sort Order:
A
B
G
C
D
E
F

How DFS Works for Topological Sorting

The algorithm uses DFS to visit nodes in depth-first manner. A node is added to the result stack only after all its dependencies (outgoing edges) have been processed. This ensures that dependencies appear before dependent nodes in the final ordering.

Key Points

  • Topological sorting only works on Directed Acyclic Graphs (DAGs)
  • DFS explores dependencies first, then adds nodes to result
  • Multiple valid topological orderings may exist for the same graph
  • Time complexity: O(V + E) where V is vertices and E is edges

Conclusion

Topological sorting using DFS provides an efficient way to order vertices in a directed graph while respecting dependencies. This algorithm is essential for scheduling tasks, resolving dependencies, and solving ordering problems in computer science.

Updated on: 2026-03-15T23:18:59+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements