from typing import AbstractSet, List, Sequence
def topological_sort(graph: Sequence[AbstractSet[int]]) -> List[int]:
"""Returns a list of nodes in topologically sorted order."""
indegrees = [0] * len(graph)
for successors in graph:
for v in successors:
indegrees[v] += 1
stack = [u for u, indegree in enumerate(indegrees) if indegree == 0]
result = []
while stack:
u = stack.pop()
result.append(u)
for v in graph[u]:
indegrees[v] -= 1
if indegrees[v] == 0:
stack.append(v)
if len(result) != len(graph):
raise ValueError('found a cycle')
return result