Skip to content

DFS-based Topological Sort

Topological sorting for a Directed Acyclic Graph (DAG) is a linear ordering of its vertices such that for every directed edge u -> v, vertex u comes before v in the ordering. DFS-based topological sort is one common method to achieve this.

  • Directed Acyclic Graph (DAG): A directed graph with no cycles.
  • DFS (Depth-First Search): A graph traversal algorithm that explores as far as possible along each branch before backtracking.
  • Finishing Time: The time at which a node’s DFS exploration is complete (i.e., all its descendants have been visited).
  1. Create an empty stack or list to store the topological order.

  2. Create a visited array or set to keep track of visited nodes, initialized to False for all nodes.

  3. For each vertex u in the graph: a. If u has not been visited: i. Call a recursive helper function dfs_util(u, visited, stack).

  4. In the dfs_util(u, visited, stack) function: a. Mark u as visited. b. For each neighbor v of u: i. If v has not been visited: 1. Recursively call dfs_util(v, visited, stack). c. After visiting all neighbors and their descendants, push u onto the stack.

  5. The topological order is obtained by popping elements from the stack.

from collections import defaultdict
class Graph:
def __init__(self, vertices):
self.graph = defaultdict(list)
self.V = vertices
def add_edge(self, u, v):
self.graph[u].append(v)
def dfs_util(self, v, visited, stack):
visited[v] = True
for i in self.graph[v]:
if not visited[i]:
self.dfs_util(i, visited, stack)
stack.append(v)
def topological_sort(self):
visited = [False] * self.V
stack = []
for i in range(self.V):
if not visited[i]:
self.dfs_util(i, visited, stack)
return stack[::-1] # Return in reverse order to get topological sort
# Example Usage
g = Graph(6)
g.add_edge(5, 2)
g.add_edge(5, 0)
g.add_edge(4, 0)
g.add_edge(4, 1)
g.add_edge(2, 3)
g.add_edge(3, 1)
print("Following is a Topological Sort of the given graph")
print(g.topological_sort())
  • Time Complexity: O(V + E), where V is the number of vertices and E is the number of edges, as each vertex and edge is visited once.
  • Space Complexity: O(V + E) for the adjacency list and O(V) for the visited array and recursion stack.