def dfs(node, graph, visited, stack): visited.add(node) for neighbor in graph.get(node, []): if neighbor not in visited: dfs(neighbor, graph, visited, stack) stack.append(node) graph = { 'A': ['B', 'C'], 'B': ['D'], 'C': ['D'], 'D': [] } visited = set() stack = [] for node in graph: if node not in visited: dfs(node, graph, visited, stack) stack.reverse() print(' -> '.join(stack) + ' -> null')
The DFS visits nodes starting from 'A'. It explores 'B' and then 'D', then backtracks to explore 'C' and 'D' (already visited). The stack after DFS is ['D', 'B', 'C', 'A'], reversing it gives ['A', 'B', 'C', 'D'] which is the correct topological order.
Topological sort requires a Directed Acyclic Graph (DAG). If there is a cycle, no linear ordering exists because tasks depend on each other in a loop, making sorting impossible.
def dfs(node, graph, visited, stack): visited.add(node) for neighbor in graph.get(node, []): if neighbor not in visited: dfs(neighbor, graph, visited, stack) stack.append(node) graph = { 'X': ['Y'], 'Y': [], 'A': ['B'], 'B': [] } visited = set() stack = [] for node in graph: if node not in visited: dfs(node, graph, visited, stack) stack.reverse() print(' -> '.join(stack) + ' -> null')
The for loop visits 'X' first, then 'Y', then 'A', then 'B'. DFS on 'X' visits 'Y', stack after is ['Y', 'X']. Then DFS on 'A' visits 'B', stack after is ['Y', 'X', 'B', 'A']. Reversing gives ['A', 'B', 'X', 'Y'].
def dfs(node, graph, visited, stack): visited.add(node) for neighbor in graph[node]: if neighbor not in visited: dfs(neighbor, graph, visited, stack) stack.append(node) graph = { 'A': ['B'], 'B': ['C'], 'C': [] } visited = set() stack = [] for node in ['A', 'B', 'C', 'D']: if node not in visited: dfs(node, graph, visited, stack) stack.reverse() print(' -> '.join(stack) + ' -> null')
The for loop includes 'D' which is not a key in the graph dictionary. Accessing graph['D'] causes a KeyError.
The graph edges impose constraints: 1 before 2 and 3, and both 2 and 3 before 4. Possible orders are:
1,2,3,4
1,3,2,4
So total 2 unique valid orders.
