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.
Key Concepts
Section titled “Key Concepts”- 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).
Algorithm Steps
Section titled “Algorithm Steps”-
Create an empty stack or list to store the topological order.
-
Create a
visitedarray or set to keep track of visited nodes, initialized toFalsefor all nodes. -
For each vertex
uin the graph: a. Ifuhas not been visited: i. Call a recursive helper functiondfs_util(u, visited, stack). -
In the
dfs_util(u, visited, stack)function: a. Markuas visited. b. For each neighborvofu: i. Ifvhas not been visited: 1. Recursively calldfs_util(v, visited, stack). c. After visiting all neighbors and their descendants, pushuonto the stack. -
The topological order is obtained by popping elements from the stack.
Python Code Example
Section titled “Python Code Example”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 Usageg = 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 and Space Complexity
Section titled “Time and Space Complexity”- 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.