In the realm of computer science, topological sorting is a linear ordering of vertices in a directed acyclic graph (DAG) such that for every directed edge \( u \rightarrow v \), vertex \( u \) comes before \( v \) in the ordering. This concept is fundamental in various applications, including scheduling tasks with dependencies, resolving software package dependencies, and more.
Topological sorting can be achieved using two main algorithms:
Both methods ensure that all directed edges respect the topological order.
Let's explore both algorithms through practical examples.
Here is a Python implementation using DFS:
1def topological_sort_dfs(graph):2def dfs_util(v, visited, stack):3visited[v] = True4for i in graph[v]:5if not visited[i]:6dfs_util(i, visited, stack)7stack.insert(0, v)89visited = {node: False for node in graph}10stack = []1112for node in graph:13if not visited[node]:14dfs_util(node, visited, stack)1516return stack1718# Example usage19graph_dfs = {20'A': ['C'],21'B': ['C', 'D'],22'C': ['E'],23'D': ['F'],24'E': [],25'F': []26}2728print("Topological Sort using DFS:", topological_sort_dfs(graph_dfs))
Topological Sort using DFS: ['A', 'B', 'D', 'C', 'E', 'F']
Here is a Python implementation using Kahn's algorithm:
1from collections import deque23def topological_sort_kahn(graph):4in_degree = {node: 0 for node in graph}5for u in graph:6for v in graph[u]:7in_degree[v] += 189queue = deque([u for u in graph if in_degree[u] == 0])10topo_order = []1112while queue:13u = queue.popleft()14topo_order.append(u)15for v in graph[u]:16in_degree[v] -= 117if in_degree[v] == 0:18queue.append(v)1920return topo_order2122# Example usage23graph_kahn = {24'A': ['C'],25'B': ['C', 'D'],26'C': ['E'],27'D': ['F'],28'E': [],29'F': []30}3132print("Topological Sort using Kahn's Algorithm:", topological_sort_kahn(graph_kahn))
Topological Sort using Kahn's Algorithm: ['A', 'B', 'D', 'C', 'E', 'F']
After mastering topological sorting, you can delve into more advanced topics such as Graph Connectivity. Understanding how to determine if a graph is connected or finding connected components will provide deeper insights into the structure and properties of graphs.