Created
June 24, 2020 16:13
-
-
Save f6v/c5f2c3f93a46fdbc7e690277c666d0cc to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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