Skip to content

Instantly share code, notes, and snippets.

@nhudinhtuan
Created April 6, 2020 12:35
Show Gist options
  • Save nhudinhtuan/60985d81b1f4ca64e2ef66b0f2d3dc4b to your computer and use it in GitHub Desktop.
Save nhudinhtuan/60985d81b1f4ca64e2ef66b0f2d3dc4b to your computer and use it in GitHub Desktop.
Topological sort
# graph is represented by adjacency list: List[List[int]]
# using DFS to find the topological sorting
def topological_sort(graph):
# using a stack to keep topological sorting
stack = []
# set is used to mark visited vertices
visited = set()
def recur(current_vertex):
# mark it visited
visited.add(current_vertex)
# Recur for all the vertices adjacent to current_vertex
for v in graph[current_vertex]:
if v not in visited:
recur(v)
# Push current vertex to stack after travelling to all neighbours
stack.append(current_vertex)
# call recur for all vertices
for u in range(len(graph)):
# Don't recur for u if it is already visited
if u not in visited:
recur(u)
# print content of the stack
print(stack[::-1])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment