We are asked: "Write a program that performs topological sort using DFS."
We need to produce a program. The instruction is generic, likely expecting code in a language such as Python, C++, Java, etc. Typically in such contexts, Python is common. We should provide a clear implementation of topological sort using depth-first search (DFS) on a directed acyclic graph (DAG). The program should read input? Possibly just a function. The problem statement is minimal. We need to decide on the input format and output.
Given the open-endedness, we can write a Python program that reads graph edges from standard input (or define a graph) and outputs a topological order.
We'll implement a class or function topological_sort_dfs(graph) that returns a list of nodes in topologically sorted order.
We'll assume the graph is given as adjacency list. For reading input, maybe first line: number of vertices and edges? Or just list of edges until EOF. Let's define a flexible approach: read from stdin, each line contains two integers u v representing directed edge from u to v. The vertices are integers. We'll collect all vertices, then build adjacency list, then perform DFS topological sort. We'll output the order as space-separated vertices.
We need to handle cycles? The problem says topological sort, which assumes DAG, but we could detect cycles and raise error or output something.
We'll implement DFS with three states: unvisited, visiting, visited. If we encounter a back edge (visiting), then cycle detected.
We'll produce the order by adding nodes to a result list after all descendants are processed (post-order), then reverse.
Let's write the code.
We'll also include a main guard.
We'll produce a complete script.
Make sure to include comments.
We'll output to stdout.
Implementation:
import sys
from collections import defaultdict
def topological_sort_dfs(graph):
"""
Perform topological sort using DFS on a directed graph.
Args:
graph: dict mapping vertex to list of neighbors (directed edges from vertex to neighbors).
Returns:
list of vertices in topological order.
Raises:
ValueError if graph contains a cycle.
"""
# states: 0 = unvisited, 1 = visiting, 2 = visited
state = {}
result = []
def dfs(v):
state[v] = 1 # visiting
for neighbor in graph.get(v, []):
if neighbor not in state: # unvisited
dfs(neighbor)
elif state[neighbor] == 1:
# back edge, cycle
raise ValueError("Graph contains a cycle, topological sort impossible.")
state[v] = 2
result.append(v)
for v in graph:
if v not in state:
dfs(v)
# The result is in reverse post-order, so reverse to get topological order.
return result[::-1]
def main():
# Read input from stdin. Assume each line contains two integers u v,
# representing a directed edge from u to v.
# If the input is empty, output nothing.
edges = []
vertices = set()
for line in sys.stdin:
line = line.strip()
if not line or line.startswith('#'):
continue
parts = line.split()
if len(parts) < 2:
continue
u, v = map(int, parts[:2])
edges.append((u, v))
vertices.add(u)
vertices.add(v)
# Build adjacency list
graph = defaultdict(list)
for u, v in edges:
graph[u].append(v)
# Ensure all vertices appear as keys in graph, even if no outgoing edges.
for v in vertices:
if v not in graph:
graph[v] = []
try:
order = topological_sort_dfs(graph)
print("Topological order:", ' '.join(map(str, order)))
except ValueError as e:
print(e)
if __name__ == "__main__":
main()
But we need to be careful: the topological sort should output only the order, maybe just the numbers. The problem says "Write a program that performs topological sort using DFS." So it's fine.
We might also want to handle the case where input format is different. However, typical programming problems give number of vertices and edges. But here it's open. I'll assume edges list.
Alternatively, we could write a more generic function that accepts number of vertices and edges.
But we can simplify: the program reads from standard input: first line contains two integers n and m (number of vertices and edges), then m lines each contain two integers u v. This is common.
Let's adapt to that common format: many online judges use that.
We'll change: read first line: n, m. Then read m lines of edges.
But if the input doesn't provide n, we could infer from vertices. However, it's safer to expect n and m.
Let's decide: we'll read first line, if it contains two numbers, treat as n and m; else treat as edge. But for simplicity, I'll go with the common format: first line: V E. Then E lines of edges.
I'll update the main accordingly.
Also, we need to ensure that we handle vertices numbered from 0 to V-1 or arbitrary. We'll just use the vertices as given.
But the graph might have vertices not appearing in edges? Possibly all vertices appear as keys.
We'll handle: after reading V and E, we know V is number of vertices, but they may be numbered from 1 to V, or 0 to V-1. We'll assume vertices are from 1 to V or 0 to V-1; we can just use the adjacency list built from edges, but we need to include vertices with no outgoing edges. Since we know V, we can iterate over range(V) or range(1, V+1) depending on the typical indexing. But the problem statement doesn't specify. To be safe, we can just collect vertices from edges and then add any missing ones from 0..V-1? But that may be wrong if vertices are 1-indexed. Actually, if they give V, they often mean vertices labeled 1..V (or 0..V-1). Usually in CP, vertices are 1-indexed. But we can't assume. Better to not rely on V for labeling; just use the vertices that appear. If they provide V, we can use it to ensure we include all vertices even if isolated. We can treat vertices as integers from 0 to V-1 or 1 to V. The input will have edges that refer to those labels. So we can create graph with keys from 0..V-1 (or 1..V). We can check: if after reading edges, the max vertex id is V or V-1? Not reliable.
Simplify: We'll not read V and E; we'll just read edges until EOF. That is more flexible. But the problem statement might expect a function. However, the instruction says "Write a program that performs topological sort using DFS." Usually in educational contexts, they want a complete runnable program. I'll provide a script that reads edges from stdin and outputs topological order. That should be acceptable.
I'll include comments explaining.
Alternatively, we can define a function topological_sort that takes adjacency list and returns order.
Given that the prompt is simple, we should output code only? Probably they expect a code block. I'll write a clean Python program.
Make sure to handle potential recursion depth for large graphs. But for typical usage, recursion is fine; we could implement iterative DFS but recursion is simpler. We'll note that for large graphs, we may need to set recursion limit.
Add: sys.setrecursionlimit(1000000)
I'll include that.
Now, let's craft the final answer.
We'll output:
"""
Topological Sort using Depth-First Search (DFS)
This program reads a directed graph from standard input and outputs a
topological ordering of its vertices. Input format: each line contains
two integers u v representing a directed edge from u to v. The graph
must be a DAG; otherwise the program reports a cycle.
"""
import sys
from collections import defaultdict
def topological_sort(graph):
"""
Perform topological sort using DFS on a directed graph.
Args:
graph: dict mapping vertex to list of neighboring vertices (directed edges).
Returns:
list of vertices in topological order.
Raises:
ValueError: if the graph contains a cycle.
"""
# state: 0 = unvisited, 1 = visiting (in current DFS path), 2 = visited
state = {}
order = []
def dfs(v):
state[v] = 1 # currently visiting
for w in graph.get(v, []):
if w not in state: # unvisited
dfs(w)
elif state[w] == 1: # back edge -> cycle
raise ValueError("Graph contains a cycle, topological sort impossible.")
state[v] = 2
order.append(v) # post-order
for v in graph:
if v not in state:
dfs(v)
# The order list is built by appending vertices after processing all descendants,
# so it is the reverse of a topological order. Reverse it.
return order[::-1]
def main():
# Increase recursion limit to handle large graphs.
sys.setrecursionlimit(1000000)
# Read all lines from stdin, skipping empty lines and comments.
edges = []
vertices = set()
for line in sys.stdin:
line = line.strip()
if not line or line.startswith('#'):
continue
parts = line.split()
if len(parts) < 2:
continue
u, v = map(int, parts[:2])
edges.append((u, v))
vertices.add(u)
vertices.add(v)
# Build adjacency list.
graph = defaultdict(list)
for u, v in edges:
graph[u].append(v)
# Ensure vertices with no outgoing edges appear in the graph dict.
for v in vertices:
graph.setdefault(v, [])
try:
ordering = topological_sort(graph)
print("Topological order:", " ".join(map(str, ordering)))
except ValueError as e:
print(e)
if __name__ == "__main__":
main()
That should be fine.
We could also output just the ordering numbers without "Topological order:". But it's fine.
Now, produce final answer.
"""
Topological Sort using Depth-First Search (DFS)
This program reads a directed graph from standard input and outputs a
topological ordering of its vertices. Input format: each line contains
two integers u v representing a directed edge from u to v. The graph
must be a DAG; otherwise the program reports a cycle.
"""
import sys
from collections import defaultdict
def topological_sort(graph):
"""
Perform topological sort using DFS on a directed graph.
Args:
graph: dict mapping vertex to list of neighboring vertices (directed edges).
Returns:
list of vertices in topological order.
Raises:
ValueError: if the graph contains a cycle.
"""
# state: 0 = unvisited, 1 = visiting (in current DFS path), 2 = visited
state = {}
order = []
def dfs(v):
state[v] = 1 # mark as visiting
for w in graph.get(v, []):
if w not in state: # unvisited
dfs(w)
elif state[w] == 1: # back edge -> cycle
raise ValueError("Graph contains a cycle, topological sort impossible.")
state[v] = 2 # mark as visited
order.append(v) # post‑order: all descendants processed
for v in graph:
if v not in state:
dfs(v)
# order is reverse post‑order, so reverse to obtain topological order
return order[::-1]
def main():
# Increase recursion limit to handle large graphs
sys.setrecursionlimit(1000000)
# Read edges from stdin
edges = []
vertices = set()
for line in sys.stdin:
line = line.strip()
if not line or line.startswith('#'):
continue
parts = line.split()
if len(parts) < 2:
continue
u, v = map(int, parts[:2])
edges.append((u, v))
vertices.add(u)
vertices.add(v)
# Build adjacency list
graph = defaultdict(list)
for u, v in edges:
graph[u].append(v)
# Ensure isolated vertices appear in the dictionary
for v in vertices:
graph.setdefault(v, [])
try:
ordering = topological_sort(graph)
print("Topological order:", " ".join(map(str, ordering)))
except ValueError as e:
print(e)
if __name__ == "__main__":
main()