Skip to content

Instantly share code, notes, and snippets.

@f6v
Created June 24, 2020 16:13
Show Gist options
  • Save f6v/c5f2c3f93a46fdbc7e690277c666d0cc to your computer and use it in GitHub Desktop.
Save f6v/c5f2c3f93a46fdbc7e690277c666d0cc to your computer and use it in GitHub Desktop.
from collections import defaultdict
def ordering(graph:dict):
in_counts = defaultdict(int)
for k, v in graph.items():
if not k in in_counts:
in_counts[k] = 0
for in_node in v:
in_counts[in_node] += 1
queue = []
for in_node in in_counts.keys():
if in_counts[in_node] == 0:
queue.append(in_node)
topological_order = []
while queue:
current_node = queue.pop(0)
topological_order.append(current_node)
if not current_node in graph:
continue
for in_node in graph[current_node]:
in_counts[in_node] -= 1
if in_counts[in_node] == 0:
queue.append(in_node)
return topological_order
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment