You are given a directed graph. Write a function to find a "topological sort" of the graph. Please what is a topological sort? What kind of graph must it be for a topological sort to exist? (Directed Acyclic Graph - DAG), describe Kahn's algorithm, which uses in-degrees of nodes and a queue, describe the alternative algorithm that uses Depth First Search (DFS) and a stack, and write the code for one of these algorithms.
Assistant
We are asked to:
Explain what a topological sort is.
What kind of graph must it be for a topological sort to exist? (Answer: Directed Acyclic Graph - DAG)
Describe Kahn's algorithm.
Describe the alternative algorithm that uses Depth First Search (DFS) and a stack.
Write the code for one of these algorithms.
Let's structure the answer:
What is a topological sort?
A topological sort (or topological ordering) of a directed graph is a linear ordering of its vertices such that for every directed edge (u, v) from vertex u to vertex v, u comes before v in the ordering. This is only possible if the graph has no directed cycles (i.e., it is a directed acyclic graph, DAG). Topological sorting has applications in scheduling tasks with dependencies, ordering of formula cell evaluation, etc.
What kind of graph?
A topological sort exists if and only if the graph is a directed acyclic graph (DAG).
Kahn's Algorithm:
Steps:
Compute in-degree (number of incoming edges) for each vertex.
Enqueue all vertices with in-degree 0 into a queue.
While the queue is not empty:
a. Dequeue a vertex and append it to the topological order.
b. For each outgoing edge from this vertex to a neighbor, decrement the in-degree of the neighbor.
c. If the in-degree of a neighbor becomes 0, enqueue it.
If the topological order contains all vertices, return it. Otherwise, there is a cycle (so topological sort not possible).
DFS-based Algorithm:
We do a DFS traversal of the graph. We maintain a stack (or list) to which we push a vertex after visiting all its descendants (i.e., after finishing the DFS from that vertex). We also need to detect cycles. We can use three colors: white (unvisited), gray (visiting), black (finished). Alternatively, we can use a visited set and a recursion stack set to detect cycles. Steps:
Initialize an empty stack and a visited set (or color array).
For each unvisited vertex, do DFS:
a. Mark the vertex as visiting.
b. For each neighbor:
If neighbor is unvisited, recursively DFS on it.
If neighbor is currently visiting (i.e., in recursion stack), then cycle detected.
c. After all neighbors are processed, mark the vertex as finished and push it onto the stack.
After DFS from all vertices, pop stack to get topological order.
Code:
We'll write code for one of them. Let's choose Kahn's algorithm because it's iterative and often easier to understand without recursion.
Assumptions:
The graph is represented as an adjacency list: a dictionary (or list of lists) where graph[u] is a list of vertices v such that there is an edge u -> v.
We have n vertices labeled from 0 to n-1 (or any hashable labels, but for simplicity we assume integers 0..n-1).
We'll return a list of vertices in topological order, or if a cycle exists, we can return an empty list or raise an exception.
Let's write the function:
python
from collections import deque
def topological_sort_kahn(graph, n):
"""
graph: adjacency list. graph[i] is a list of neighbors (i -> neighbor).
n: number of vertices (vertices are 0 to n-1)
Returns: list of vertices in topological order, or empty list if cycle exists.
"""
# Calculate in-degree for each vertex
in_degree = [0] * n
for u in range(n):
for v in graph[u]:
in_degree[v] += 1
# Queue for vertices with in-degree 0
queue = deque([u for u in range(n) if in_degree[u] == 0])
topo_order = []
while queue:
u = queue.popleft()
topo_order.append(u)
for v in graph[u]:
in_degree[v] -= 1
if in_degree[v] == 0:
queue.append(v)
# Check if we visited all vertices
if len(topo_order) == n:
return topo_order
else:
return [] # cycle exists
Alternatively, if the graph vertices are not necessarily 0..n-1 but arbitrary hashable, we can adjust. But the problem statement says "directed graph", so we can assume we have a list of vertices and adjacency list. We'll keep it simple.
Alternative DFS version:
But we'll write one. Since the problem says "write the code for one of these algorithms", we can choose either.
Let's also note: In the DFS version, we must be careful to push the vertex after processing all its neighbors. We can do:
python
def topological_sort_dfs(graph, n):
visited = [False] * n
stack = []
# We need to detect cycles, so we can use a recursion stack set.
rec_stack = [False] * n # to detect back edges
def dfs(u):
visited[u] = True
rec_stack[u] = True
for v in graph[u]:
if not visited[v]:
if not dfs(v):
return False
elif rec_stack[v]:
# cycle detected
return False
rec_stack[u] = False
stack.append(u)
return True
for u in range(n):
if not visited[u]:
if not dfs(u):
return [] # cycle
return stack[::-1] # reverse stack to get topological order
But note: The DFS version as above does cycle detection. However, the problem says "describe the alternative algorithm that uses DFS and a stack", so we can explain it.
Now, let's put everything together in a coherent answer.
Topological Sort
A topological sort (or topological ordering) of a directed graph is a linear ordering of its vertices such that for every directed edge ((u, v)) from vertex (u) to vertex (v), (u) comes before (v) in the ordering. This ordering is only possible if the graph has no directed cycles—that is, it must be a Directed Acyclic Graph (DAG). Topological sorting is commonly used in task scheduling, dependency resolution, and compiling.
Required Graph Property
A topological sort exists if and only if the graph is a directed acyclic graph (DAG). If the graph contains a cycle, it is impossible to linearly order the vertices while respecting all edge directions.
Kahn's Algorithm (Using In-Degrees and a Queue)
Steps:
Compute the in-degree (number of incoming edges) for each vertex.
Initialize a queue with all vertices having in-degree 0.
While the queue is not empty:
Dequeue a vertex (u) and append it to the topological order.
For each neighbor (v) of (u) (i.e., for each edge (u \rightarrow v)):
Decrement the in-degree of (v).
If the in-degree of (v) becomes 0, enqueue (v).
If the topological order contains all vertices, return it. Otherwise, a cycle exists, and no topological sort is possible.
Complexity: (O(V + E)), where (V) is the number of vertices and (E) the number of edges.
DFS-Based Algorithm (Using a Stack)
Steps:
Perform a depth-first search (DFS) traversal of the graph.
Maintain a stack (or list) to store vertices in reverse postorder—push a vertex onto the stack after recursively visiting all its descendants.
Use a visited set and a recursion stack (or "on-stack" set) to detect cycles:
Mark a vertex as visited when first encountered.
Mark it as being in the recursion stack during DFS.
If during DFS we encounter a vertex already in the recursion stack, a cycle is detected.
After finishing the DFS from a vertex, remove it from the recursion stack.
After DFS from all vertices, pop from the stack (or reverse it) to obtain the topological order.
Complexity: (O(V + E)) with cycle detection.
Code: Kahn's Algorithm
Below is a Python implementation of Kahn's algorithm. The graph is represented as an adjacency list for vertices labeled (0) to (n-1). The function returns a topological order as a list; if a cycle is detected, it returns an empty list.
python
from collections import deque
def topological_sort_kahn(graph, n):
"""
Perform topological sort using Kahn's algorithm.
Parameters:
- graph: adjacency list where graph[u] contains all v such that u -> v.
- n: number of vertices (0 to n-1)
Returns:
- List of vertices in topological order, or empty list if cycle exists.
"""
# Step 1: Compute in-degree for each vertex.
in_degree = [0] * n
for u in range(n):
for v in graph[u]:
in_degree[v] += 1
# Step 2: Initialize queue with vertices of in-degree 0.
queue = deque([u for u in range(n) if in_degree[u] == 0])
topo_order = []
# Step 3: Process queue.
while queue:
u = queue.popleft()
topo_order.append(u)
for v in graph[u]:
in_degree[v] -= 1
if in_degree[v] == 0:
queue.append(v)
# Step 4: Check for cycle.
if len(topo_order) == n:
return topo_order
else:
return [] # Cycle detected, no topological sort.
Usage Example:
python
# Example graph: 0 -> 1, 0 -> 2, 1 -> 2, 2 -> 3
graph = [[1, 2], [2], [3], []]
n = 4
print(topological_sort_kahn(graph, n)) # Output: [0, 1, 2, 3] or [0, 2, 1, 3] etc.
This implementation assumes vertices are numbered (0) to (n-1). For arbitrary vertex labels, adjust to use dictionaries or hash maps for in-degree tracking.