def top_sort(graph):
order, enter, state = [], set(graph), {}<EOL>def is_ready(node):<EOL><INDENT>lst = graph.get(node, ())<EOL>if len(lst) == <NUM_LIT:0>:<EOL><INDENT>return True<EOL><DEDENT>for k in lst:<EOL><INDENT>sk = state.get(k, None)<EOL>if sk == GRAY: <EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>if sk != BLACK:<EOL><INDENT>return False<EOL><DEDENT><DEDENT>return True<EOL><DEDENT>while enter:<EOL><INDENT>node = enter.pop()<EOL>stack = []<EOL>while True:<EOL><INDENT>state[node] = GRAY<EOL>stack.append(node)<EOL>for k in graph.get(node, ()):<EOL><INDENT>sk = state.get(k, None)<EOL>if sk == GRAY: <EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>if sk == BLACK: <EOL><INDENT>continue<EOL><DEDENT>enter.discard(k)<EOL>stack.append(k)<EOL><DEDENT>while stack and is_ready(stack[-<NUM_LIT:1>]):<EOL><INDENT>node = stack.pop()<EOL>order.append(node)<EOL>state[node] = BLACK<EOL><DEDENT>if len(stack) == <NUM_LIT:0>:<EOL><INDENT>break<EOL><DEDENT>node = stack.pop()<EOL><DEDENT><DEDENT>return order<EOL>
Time complexity is the same as DFS, which is O(V + E)
        Space complexity: O(V)