Skip to content

Instantly share code, notes, and snippets.

@evanthebouncy
Created September 7, 2025 16:30
Show Gist options
  • Save evanthebouncy/af27e23286d68c77ec56f507cd68fd9b to your computer and use it in GitHub Desktop.
Save evanthebouncy/af27e23286d68c77ec56f507cd68fd9b to your computer and use it in GitHub Desktop.
topological sort
E = { "A": ["E"],
"B": ["A", "C", "G"],
"C": ["A"],
"D": ["B", "G"],
"E": ["F"],
"F": [],
"G": ["A", "F"],
}
class Toposort:
def __init__(self):
self.visited = []
def DFS(self, node, graph):
for x in graph.get(node, []):
if x not in self.visited:
self.DFS(x, graph)
self.visited = [node] + self.visited
def toposort(self, graph):
for node in graph:
if node not in self.visited:
self.DFS(node, graph)
return self.visited
if __name__ == "__main__":
ts = Toposort()
print(ts.toposort(E))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment